- Home
- /
- If else conditionals
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- If else conditionals
If else conditionals
In programming, decisions are everything. That’s where if...else statements come in—they help your code make choices.
Let’s say you want your website to display a message only if a user is logged in, or you want to change the background color depending on the time of day. With if and else, you can do exactly that.
Basic Idea
In JavaScript, the if statement checks whether something is true. If it is, it runs a block of code. If it’s not, you can use an else to tell the browser what to do instead.
Here’s how it looks:
if (condition) {
// do this if condition is true
} else {
// do this if condition is false
}
Example
Let’s try a real example:
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
} else {
console.log("x is not greater than 5");
}
Here, JavaScript checks the condition x > 5. Since 10 is indeed greater than 5, it prints:
“x is greater than 5”
But if you changed x to 3, you’d get:
“x is not greater than 5”
This is the foundation of logic in your code. You can extend this further using else if to check multiple conditions.