JavaScript ยท Chapter 29 of 55
JavaScript If...Else
Conditional statements let a program make decisions. `if` runs a block only when a condition is true; `else if` checks another condition; `else` catches everything else.
Conditions are typically comparison or logical expressions, evaluated for truthiness before choosing which branch to execute.
Basic if/else
`if (condition) { ... } else { ... }` runs one block or the other, never both.
else if chains
Multiple `else if` blocks let you check several conditions in sequence, stopping at the first true one.
Example 1 (javascript)
let age = 20;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}Output
AdultThe condition age >= 18 is true, so the if-block runs.
Example 2 (javascript)
let score = 75;
if (score >= 90) {
console.log("A");
} else if (score >= 70) {
console.log("B");
} else {
console.log("C");
}Output
BOnly the first matching condition's block executes.
Key points
- if runs code only when its condition is truthy.
- else if allows checking multiple conditions in order.
- else runs when no prior condition matched.
- Only one branch of an if/else chain ever executes.
๐ก Note: Curly braces are optional for single-statement blocks but recommended for clarity and to prevent bugs.
