JavaScript Tutorial ✦
if...else Statement
It is used to control the flow of the code.
When the condition inside the if
block is true, it will execute the code inside the {}
curly braces.
If the condition is not met, it will not run that block of code.
If you want to run a different block of code when the if
condition is not met, you can write that code inside the else
block.
Syntax:
if (condition) {
// block of code that runs when condition is true
} else {
// block of code that runs when condition is false
}
Example:
if (name === "Alan") {
console.log("Your name is Alan"); // when the condition is true
} else {
console.log("You are not Alan"); // when the condition is false
}
Also, you can write another condition inside the else
block using another if
.
This is useful when you want to check multiple things one after another.
For example, if you want to check if a person’s age is above 20, and if not, then check if they are at least 18, you can write it like this:
if (age >= 20) {
console.log("Above 20 aged");
} else {
if (age >= 18) {
console.log("You are aged more than 18 but not more than 20");
}
}
That’s how you can use if-else
statements. It’s a crucial part in every programming language and can be used in many ways — nested, non-nested, etc.
if (age >= 18) {
console.log('Adult');
} else {
console.log('Minor');
}