Decisions: if, else and switch

Introduction

Up to now, every line of a program has run. Real programs need to choose: is this password long enough, is this student passing, is the cart empty? A condition is a question whose answer decides which code runs next. Nearly all program logic, however complicated it looks, is built from these small choices.

How it works

Comparing.

OperatorMeans
===equal
!==not equal
<, <=less, less or equal
>, >=greater, greater or equal

Conditions combine with three logical operators: && (and: both sides true), two bars (or: at least one side true, as in day === "Fri" || day === "Sat") and ! (not). JavaScript stops as soon as it knows the answer, so in x !== null && x.size > 3 the second part is never reached when x is null.

if, else if, else. if (condition) { ... } runs the block only when the condition is true. else if tries another condition, and else runs when none was true. Only one block runs, so the order of the tests matters.

Truthy and falsy. A condition does not have to be a boolean. These values count as false (falsy): false, 0, "" (the empty string), null, undefined and NaN. Every other value is truthy, even "0" and []:

// Which values count as true in a condition?
const values = [0, 1, "", "0", null, undefined, [], "hi"];
for (const v of values) {
  if (v) {
    console.log(v, "is truthy");
  } else {
    console.log(v, "is falsy");
  }
}
Open in compiler

Shorter forms. The ternary operator chooses between two values: const label = age >= 18 ? "adult" : "minor";. A switch compares one value against many cases. Each case needs a break, or the next case runs too:

switch (day) {
  case "Fri":
  case "Sat":
    console.log("weekend");
    break;
  default:
    console.log("weekday");
}

Syntax

if (score >= 80) {
  grade = "A";
} else if (score >= 60) {
  grade = "B";
} else {
  grade = "C";
}

const word = count === 1 ? "item" : "items";

Example

prompt() reads a line of input as a string, so the program converts it with Number. The visualizer shows each condition being checked with its real values. This example is given the input 72.

// Read a score and print its grade.
const score = Number(prompt("Your score?"));
let grade;
if (score >= 80) {
  grade = "A";
} else if (score >= 60) {
  grade = "B";
} else if (score >= 40) {
  grade = "C";
} else {
  grade = "F";
}
console.log(`Score ${score}: grade ${grade}`);
const passed = score >= 40 ? "passed" : "did not pass";
console.log("You", passed);

Input used: 72

Open in compiler

Line by line

  1. The input is read and converted to a number.
  2. let grade; is declared before the if, so that it is still visible after it.
  3. 72 >= 80 is false, so the first block is skipped.
  4. 72 >= 60 is true, so grade becomes "B". The remaining tests are never made, which is why the second test needs no "and less than 80".
  5. The first console.log prints the score and grade.
  6. The ternary picks one of two texts, and the last line prints it.

Expected result

Score 72: grade B
You passed

In the real world

Checkout pages use conditions to apply a delivery fee only below a certain total. Login forms show one message for a wrong password and another for a locked account. Games decide what happens on each collision. When you read code, try to read each condition aloud as a question.

Common mistakes

  • Writing if (x = 5). One = stores a value. Compare with ===.
  • Writing if (1 < x < 5). It is worked out as (1 < x) < 5. Write if (1 < x && x < 5).
  • Forgetting break in a switch, so the next case runs as well.
  • Comparing input to a number without converting. prompt() gives a string.
  • Putting a broad test first. If score >= 40 comes before score >= 80, the higher grade is never reached.

Best practices

  • Put the most specific or most restrictive test first.
  • Give a long condition a name: const canVote = age >= 18 && isCitizen;.
  • Return early from a function to avoid deep nesting.
  • Use a ternary only for simple choices between two values.

Summary

Comparisons give true or false, and &&, two bars and ! combine them. An if chain runs only the first matching block. Falsy values count as false in a condition. The ternary picks between two values, and switch compares one value with many cases.

Quick check

1. Which of these values is falsy?
2. x = 7. What does x > 5 && x < 10 give?
3. In an if / else if / else chain, how many blocks run?
4. What happens without break at the end of a switch case?

Key takeaways

  • Only the first true branch of an if chain runs.
  • Conditions use truthy and falsy values, not only true and false.
  • Test the most specific case first.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.