if, else if, else Statements
Conditionals let your program make decisions. The if statement runs code only when a condition is true. else runs when false. else if checks additional conditions. This is how programs respond differently to different inputs.
Conditional Logic
- if (condition) { } — Runs code block if condition is true
- else { } — Runs if the condition is false
- else if (condition) { } — Checks another condition if the first was false
- You can chain multiple else if blocks — only the first matching block executes
- Conditions use comparison operators: >, <, ===, !==, >=, <=
- Combine conditions with && (AND) and || (OR)
if/else Code
// Basic if/else
const age = 18;
if (age >= 18) {
console.log("You can vote! ✅");
} else {
console.log("Too young to vote ❌");
}
// else if chain
const score = 75;
if (score >= 90) {
console.log("Grade: A — Excellent!");
} else if (score >= 80) {
console.log("Grade: B — Great!");
} else if (score >= 70) {
console.log("Grade: C — Good");
} else if (score >= 60) {
console.log("Grade: D — Needs work");
} else {
console.log("Grade: F — Please study more");
}
// Combined conditions
const hasID = true;
const isAdult = age >= 18;
if (isAdult && hasID) {
console.log("Entry allowed");
} else {
console.log("Entry denied");
}Try It Yourself: Grade Calculator
Tip
Tip
Store conditions in descriptive boolean variables before using them in if statements. Instead of if (age >= 18 && hasID && !isBanned), write const canEnter = age >= 18 && hasID && !isBanned; if (canEnter) — much more readable.
?? only checks null/undefined, || checks all falsy.
Common Mistake
Warning
Using = (assignment) instead of === (comparison) inside if conditions. if (x = 5) assigns 5 to x and always evaluates as truthy. Always use === for comparisons: if (x === 5).
Practice Task
Note
Build a ticket pricing system: (1) If age < 5, free entry. (2) If age < 18, half price. (3) If age >= 65, senior discount. (4) Otherwise, full price. Test with ages 3, 12, 25, and 70.
Quick Quiz
Key Takeaways
- Conditionals let your program make decisions.
- if (condition) { } — Runs code block if condition is true
- else { } — Runs if the condition is false
- else if (condition) { } — Checks another condition if the first was false