Loading lessons...
JavaScript If and Else
JavaScript If and Else
Use if and else to make decisions in your code.
The if statement
if (age >= 18) {
console.log("Adult");
}
If the condition in parentheses is true, the code in the block runs.
if and else
if (hour < 12) {
console.log("Good morning");
} else {
console.log("Good afternoon");
}
If the condition is false, the else block runs instead.
else if
Check multiple conditions in order:
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else {
console.log("Try again");
}
JavaScript checks each condition from top to bottom and runs the first one that is true.
Comparison conditions
Conditions usually use comparison operators like ===, >, <, and logical operators like && and ||.
TL;DR
ifruns code when a condition is true.elseruns when the condition is false.else ifchecks more conditions in order.- Only the first true block runs.