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:

Example 1Try it yourself
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:

Example 2Try it yourself
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:

Example 3Try it yourself
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?

  1. One
  2. Two
  3. All that are true
  4. None
Show answer

Answer: One