edubun 한국어

Making decisions with if and else

An if statement runs a block of code only when its condition is true. With else if, JavaScript checks conditions from the top and stops at the first true one.

Running code only sometimes

Every program so far has run each line, every time. Useful programs behave differently in different situations: a game shows "You win" only when the score is high enough, and a shop adds a delivery fee only when the order is small. The if statement is how JavaScript chooses.

const temperature = 31;
if (temperature >= 30) {
  console.log("Hot day. Drink water.");
}
console.log("Done");

The condition goes in parentheses after the word if. It is any expression that produces a boolean, usually a comparison from the last unit. The code to run when it is true goes inside curly braces, which form a block. If the condition is false, JavaScript skips the whole block and carries on after the closing brace. Above, both lines print. Change temperature to 20 and only "Done" prints. The lines inside the block are indented by two spaces. JavaScript does not need the indentation, but it shows at a glance which lines belong to the if, and every experienced programmer will expect it.

else: the other path

Often you want one thing when the condition is true and something else when it is false. Add an else block. Exactly one of the two blocks runs, never both and never neither.

const n = 7;
if (n % 2 === 0) {
  console.log(n + " is even");
} else {
  console.log(n + " is odd");
}
// prints: 7 is odd

else if: more than two choices

For several possibilities, chain conditions with else if. JavaScript tests them from the top. As soon as one is true it runs that block and skips all the rest, even if later conditions would also be true. The final else catches everything that matched nothing above.

const score = 72;
if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else if (score >= 70) {
  console.log("C");
} else {
  console.log("F");
}
// prints: C

The order of the conditions matters. With a score of 95, the first test is already true and A prints. If the tests were written the other way round, starting with score >= 70, a score of 95 would stop at the first test and print C. When the ranges overlap like this, put the narrowest condition first. Tracing code by hand is a good habit: pick a value, read from the top, and say out loud which branch it takes.

Nesting and combining

A block can contain another if statement, which is called nesting. Often you can avoid deep nesting by combining conditions with && and || from the last unit. These two pieces of code do the same job, and the second is easier to read:

if (age >= 8) {
  if (height >= 120) {
    console.log("You can ride");
  }
}

if (age >= 8 && height >= 120) {
  console.log("You can ride");
}

The conditional operator

When you only need to pick between two values, there is a compact form called the conditional (ternary) operator: condition ? valueIfTrue : valueIfFalse. For example, const label = n % 2 === 0 ? "even" : "odd";. Use it for short choices of a value. For anything that runs several statements, a normal if and else is clearer.

A common slip is writing one equals sign inside the condition: if (score = 100). That stores 100 in score instead of comparing, and the block runs every time. Always compare with ===.

if (condition) { ... } else if (other condition) { ... } else { ... }

conditionThe boolean expression in if ( )
blockStatements grouped in { }
elseRuns when the if condition is false
else ifAnother condition, checked only if the ones above were false
branchOne of the possible paths through an if statement
nestingAn if inside another if
ternarycond ? a : b picks one of two values
indentationSpaces at the start of lines inside a block
  1. What does this print?
    const x = 5;
    if (x > 3) {
      console.log("big");
    } else {
      console.log("small");
    }
  2. What does this print?
    const x = 2;
    if (x > 3) {
      console.log("big");
    }
    console.log("end");
    • big, then end
    • Only end
    • Nothing
  3. What does this print?
    const t = 18;
    if (t >= 30) {
      console.log("hot");
    } else if (t >= 15) {
      console.log("mild");
    } else {
      console.log("cold");
    }
  4. What does this print?
    const s = 95;
    if (s >= 70) {
      console.log("C");
    } else if (s >= 90) {
      console.log("A");
    }
  5. In an if / else if / else chain, how many blocks run at most?
  6. What does this print?
    const n = 10;
    console.log(n > 5 ? "yes" : "no");
  7. What does this print?
    const a = 4;
    const b = 9;
    if (a > 5 || b > 5) {
      console.log("one");
    } else {
      console.log("none");
    }
  8. What does this print?
    const a = 4;
    const b = 9;
    if (a > 5 && b > 5) {
      console.log("both");
    } else {
      console.log("not both");
    }
  9. What is wrong with if (score = 100)?
    • Nothing
    • It stores 100 instead of comparing; use ===
    • It needs a semicolon inside
  10. What does this print?
    let msg = "start";
    const n = 0;
    if (n) {
      msg = "nonzero";
    }
    console.log(msg);
Key points
  • if (condition) { ... } runs the block only when the condition is true.
  • else runs when it is false; exactly one of the two runs.
  • else if chains are checked from the top; the first true one wins.
  • Put the narrowest condition first when ranges overlap.
  • Compare with ===, never a single =.