if / else

Understand how to make a program branch and execute different code paths using if, else, and else if, and how JavaScript decides whether a value counts as true or false.

Control flow is what turns a script into a program that can make decisions. The if statement is the most fundamental tool for that: it lets code run only when a condition holds, and skip or replace itself with something else when it does not.

The if statement

An if statement evaluates a condition inside parentheses. If that condition is truthy, the block of code in curly braces runs; if it is falsy, the block is skipped entirely and execution continues after it.

The condition can be any expression that produces a value — a comparison like age >= 18, a boolean variable, or even a function call that returns true or false. JavaScript converts whatever the expression produces into a boolean behind the scenes to decide which branch to take.

else: the alternative path

An else block attaches to an if and runs only when the if's condition was falsy. Together, if/else guarantees that exactly one of the two blocks executes — never both, never neither.

Using else instead of two separate if statements is not just style: it also communicates to any reader that the two branches are mutually exclusive, and it can save an unnecessary condition check when the first one already failed.

else if: chaining multiple conditions

When there are more than two possible outcomes, else if lets you chain additional conditions after the first if. JavaScript checks each condition in order, top to bottom, and runs the first block whose condition is truthy — every condition after that is skipped, even if it would also have been true.

A final else at the end of the chain acts as a catch-all for anything that did not match any of the earlier conditions. It is optional, but including one is often good practice so that every possible case is handled deliberately.

Nested conditions

An if/else block can contain another if/else inside it. This is called nesting, and it is useful when a decision genuinely depends on first satisfying an outer condition before a more specific inner condition even makes sense to check.

Nesting should be used carefully — deeply nested conditions (three or four levels deep) become hard to read and debug. Often a nested structure can be flattened using else if chains, early returns inside a function, or by combining conditions with && and ||.

Truthy and falsy values

Every JavaScript value has an inherent boolean identity when used in a condition, even if it is not literally true or false. Values that behave like false in a condition are called falsy; everything else is truthy.

There are exactly six falsy values in JavaScript (plus NaN, which is technically its own case): false, 0, "" (empty string), null, undefined, and NaN. Every other value — including "0" (a non-empty string), [] (an empty array), and {} (an empty object) — is truthy, which surprises many beginners.

• Falsy: false, 0, -0, 0n, "", null, undefined, NaN • Truthy: everything else, including "0", "false", [], {}, and any function

if / else if / else structure

Only one branch ever executes per pass through the chain. Conditions are checked top to bottom; the first truthy one wins and the rest are never evaluated. The else block is optional — you can have a bare if, or an if/else with no else if in between.

if (condition1) {
  // runs when condition1 is truthy
} else if (condition2) {
  // runs when condition1 is falsy AND condition2 is truthy
} else {
  // runs when none of the above conditions were truthy
}

Code Examples

The condition age >= 18 evaluates to true, so only the first block runs — the else block is skipped completely. Expected result: You can vote.

if (age >= 18) is the condition; because it is truthy, execution never reaches the else block.

This chains three conditions to cover four possible ranges. Since a return statement exits the function immediately, only one branch ever runs, and the checks below it never fire. Expected result: B F else if (score >= 80) only runs because the first condition (score >= 90) was already falsy for 85.

Common mistake: Writing separate if statements instead of else if would waste time checking conditions that could not possibly matter once an earlier one matched, and can even produce wrong results if the ranges overlap.

const age = 20;

if (age >= 18) {
  console.log("You can vote.");
} else {
  console.log("You are not old enough to vote yet.");
}
function gradeLabel(score) {
  if (score >= 90) {
    return "A";
  } else if (score >= 80) {
    return "B";
  } else if (score >= 70) {
    return "C";
  } else {
    return "F";
  }
}

console.log(gradeLabel(85));
console.log(gradeLabel(55));

if / else if / else decision flow

Only one path is ever taken; once a branch runs, execution rejoins the main flow after the entire if/else if/else chain.

condition1?
          /          \
       true          false
        |              |
   run block 1    condition2?
        |         /        \
        |      true        false
        |       |            |
        |  run block 2   run else block
        |       |            |
        └───────┴────────────┘
                 ↓
         continue program

Important Rules

Only one block in an if/else if/else chain executes, no matter how many conditions would also be true.

Conditions are evaluated top to bottom, and evaluation stops at the first truthy one.

Falsy values are exactly: false, 0, -0, 0n, "", null, undefined, and NaN — everything else is truthy.

Curly braces can technically be omitted for a single-statement block, but omitting them is a common source of bugs and is best avoided.

else and else if are optional; a bare if with no else is perfectly valid.

Where this shows up

Form validation (checking whether a password meets length requirements before submitting), access control (showing an admin panel only if a user's role qualifies), and UI logic (displaying a discount only when a cart total crosses a threshold) all rely directly on if/else chains.

if (score = 90) {... } if (score === 90) {... } A single = is assignment, not comparison. score = 90 assigns 90 to score and the condition becomes truthy simply because 90 is a truthy number — this silently overwrites the variable and produces a hard-to-spot bug. Always use === (or == when intentionally loose) for comparisons.

if (isLoggedIn == "true") if (isLoggedIn === true) Comparing a boolean to the string "true" with loose equality relies on type coercion rules that are easy to get wrong; using strict equality (===) with matching types is clearer and avoids surprises.

[Multiple Choice] Which of the following values is truthy in JavaScript? A. 0 B. "" C. "0" D. null

C. "0" — "0" is a non-empty string, and non-empty strings are always truthy — only the exact value 0 (the number), the empty string "", and null/undefined/NaN/false are falsy.

[True / False] In an if/else if/else chain, more than one block can run during a single pass if multiple conditions are true. A. True B. False

B. False — False. Only the first branch whose condition is truthy runs; every condition after it is skipped, even if it would also evaluate to true.

Write a function classifyTemperature(tempC) that returns "Freezing" for 0 or below, "Cold" for 1–15, "Mild" for 16–25, and "Hot" for anything above 25.

function classifyTemperature(tempC) { if (tempC <= 0) { return "Freezing"; } else if (tempC <= 15) { return "Cold"; } else if (tempC <= 25) { return "Mild"; } else { return "Hot"; } }

Order your else if checks from the lowest boundary to the highest, or from highest to lowest — just make sure the boundaries do not overlap or leave gaps.