Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 156 ยท Control Flow

Conditionals: if, else if and else

Make decisions in JavaScript with if, else if and else. Learn how conditions are tested, how blocks work, nesting, and clean guard clauses.

So far every program in this course has run straight from top to bottom, one line after another. Real programs need to make decisions: show a discount only to members, warn when a password is too short, pick a greeting based on the time of day. In JavaScript, the most basic tool for making a decision is the if statement.

This lesson covers if, else and else if, how JavaScript decides whether a condition "passes", how to nest conditions without losing track, and a habit that keeps your code flat and readable: the guard clause.

The if statement

An if statement runs a block of code only when a condition is true:

JavaScript
if (condition) {
  // runs only when condition is truthy
}

The condition goes in parentheses. The code to run goes in a block, the curly braces. If the condition passes, the block runs; if not, JavaScript skips the whole block and continues with the next statement.

JS A first if statement

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Change temperature to 20 and run it again. The first message disappears, but the last line still prints, because it sits outside the block.

else: the other path

Often you want to do one thing when the condition passes and something else when it doesn't. Add an else block:

JS if...else

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exactly one of the two blocks runs, never both and never neither. That guarantee is what makes if...else useful: every possible value of itemsInCart lands in one branch.

Conditions are truthy or falsy

The condition doesn't have to be a real true or false. JavaScript converts whatever you put in the parentheses to a boolean, using the rules from Booleans and Truthiness. As a reminder, these values are falsy:

  • false
  • 0, -0 and 0n
  • "" (an empty string)
  • null and undefined
  • NaN

Everything else is truthy, including "0", "false", [] and {}. That lets you write short checks like this:

JS Truthy and falsy conditions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Watch out for 0. A check like if (price) fails when the price is 0, which may be a perfectly valid value. When zero or an empty string is meaningful, compare explicitly: if (price !== undefined) or if (price >= 0).

Conditions are usually built from the operators you met earlier: comparisons such as ===, < and >= from Comparison and Equality, combined with &&, || and ! from Logical Operators.

JavaScript
if (age >= 18 && hasTicket) { /* let them in */ }
if (isAdmin || isOwner) { /* show the edit button */ }
if (!isLoggedIn) { /* show the sign-in link */ }

Chains with else if

When there are more than two possibilities, chain extra conditions with else if. JavaScript tests them in order, top to bottom, and runs the first block whose condition passes. The rest are skipped, even if they would also be true.

JS Grading with else if

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A score of 95 is also >= 80 and >= 70, but only the first matching branch runs, so it gets an "A". This means order matters. If you put score >= 60 first, every passing score would become a "D".

The final else is optional. Without it, a chain might run no block at all. Include one when you want a guaranteed fallback.

else if is not a special keyword. It is just an else whose body is another if statement. JavaScript reads else if (x) { โ€ฆ } as else { if (x) { โ€ฆ } }. That's why you can chain as many as you like.

Blocks and braces

Strictly speaking, if controls a single statement, and a block in braces counts as one statement. So JavaScript allows you to drop the braces when there's only one line:

JavaScript
if (isMuted) console.log("Sound is off");

It works, but it's a trap waiting to spring. Add a second line later and only the first one is controlled by the if:

JavaScript
if (isMuted)
  console.log("Sound is off");
  showMuteIcon(); // always runs! the indentation is misleading

Most style guides, and this course, always use braces. Indentation means nothing to JavaScript; braces are what count.

Variables declared with let or const inside a block exist only inside that block:

JavaScript
if (true) {
  const message = "inside";
}
console.log(message); // ReferenceError: message is not defined

You'll learn the full rules in Scope and Hoisting. For now, declare a variable before the if when you need it afterward.

Nesting conditions

An if can sit inside another if. This is handy when a second question only makes sense once the first is answered:

JS Nested conditions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

One or two levels are fine. Beyond that, nested code drifts to the right and becomes hard to follow, because you have to keep every enclosing condition in your head. Two techniques help:

  • Combine conditions with && when the inner if has no else: if (user.loggedIn && user.role === "admin").
  • Use guard clauses, described next.

Guard clauses: exit early

A guard clause checks for a problem at the start of a function and leaves immediately with return. Once the bad cases are out of the way, the main logic can run at the top level, without being wrapped in a big if.

Compare these two versions of the same function:

JS Nested vs guard clauses

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both functions behave identically, but the second reads like a checklist. Each guard is a one-line if with a return, which is one of the few places where many developers happily skip the braces, because nothing else can sneak into the body. You'll see more about return in Return Values.

Common mistakes

  • Using = instead of ===. if (status = "done") assigns "done" to status, and the condition is always truthy. Use === to compare.
  • A stray semicolon. if (ready); { start(); } ends the if at the semicolon, so the block after it always runs.
  • Overlapping ranges in the wrong order. In an else if chain, put the most specific or highest condition first.
  • Comparing with ==. Loose equality converts types in surprising ways ("" == 0 is true). Stick with === and !==.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this code print? const n = 0; if (n) { console.log("yes"); } else { console.log("no"); }

    0 is falsy, so the condition fails and the else block runs.
  2. 2. In a chain of if (x > 10) โ€ฆ else if (x > 5) โ€ฆ else if (x > 0) โ€ฆ, which block runs when x is 20?

    JavaScript tests the conditions in order and runs only the first block whose condition passes. The rest are skipped.
  3. 3. Which value is truthy?

    Every object is truthy, including an empty array. Check .length when you want to know whether an array has items.
  4. 4. What is a guard clause?

    A guard clause handles a bad case at the top of a function and returns early, which keeps the rest of the function flat.
  5. 5. What is wrong with if (role = "admin") { โ€ฆ }?

    A single = assigns. The assignment's value, the non-empty string "admin", is truthy, so the block always runs. Use ===.

Summary

  • if (condition) { โ€ฆ } runs a block only when the condition is truthy.
  • else adds a second path; exactly one of the two blocks runs.
  • else if chains are tested top to bottom, and only the first matching branch runs, so order matters.
  • Any value can be a condition; falsy values are false, 0, "", null, undefined and NaN. Empty arrays and objects are truthy.
  • Always use braces, compare with ===, and keep nesting shallow.
  • Guard clauses handle bad cases first and return early, leaving the main logic easy to read.

Next: The Ternary Operator and switch โ€” two more compact ways to choose between values and paths.