JavaScript Tutorial · Control Flow · Lesson 14 of 44
JavaScript If Else
Run code conditionally with if, else if and else.
if
An if statement runs a block only when its condition is truthy:
const hour = 9;
if (hour < 12) {
console.log("Good morning!");
}
Output
Good morning!
else if and else
Chain conditions — the first true branch runs and the rest are skipped:
const score = 72;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
console.log(`Score ${score} → grade ${grade}`);
Output
Score 72 → grade C
Guard clauses
Instead of deep nesting, return early when a condition isn't met. This keeps the "happy path" un-indented and easy to read:
function checkout(cart) {
if (!cart) return "No cart";
if (cart.items.length === 0) return "Cart is empty";
return `Paying for ${cart.items.length} items`;
}
console.log(checkout(null));
console.log(checkout({ items: [] }));
console.log(checkout({ items: ["book", "pen"] }));
Output
No cart Cart is empty Paying for 2 items
Test yourself
In an if / else if / else chain, how many branches run at most?
OneTwoAll that are trueNone
Show answer
Answer: One