Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 156 ยท Control Flow

The Ternary Operator and switch

Choose values with the ternary operator, branch on many cases with switch, understand fallthrough, and learn when a lookup object beats both.

The if statement from the previous lesson can express any decision, but it isn't always the neatest tool. When you just need to pick one of two values, an if...else with two assignments feels clumsy. And when you compare one value against a long list of possibilities, an else if chain gets repetitive.

JavaScript has two tools for those situations: the conditional (ternary) operator ? : for choosing between two values, and the switch statement for matching one value against many cases. This lesson covers both, including switch's famous "fallthrough" behavior, and then shows a third option that often beats them: a plain lookup object.

The ternary operator

The ternary operator takes three parts, which is where its name comes from:

JavaScript
condition ? valueIfTruthy : valueIfFalsy

JavaScript evaluates the condition. If it's truthy, the whole expression produces the value after ?; otherwise it produces the value after :. Because it's an expression, it gives back a value you can store, return, log or put inside a template literal. An if statement can't do that.

JS Choosing a value

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

No output.

The template-literal case is where the ternary shines: small, inline choices such as singular vs plural, "on" vs "off", or a CSS class name.

Keep ternaries simple

You can chain ternaries, because the part after : may itself be another ternary:

JavaScript
const size = width < 600 ? "small" : width < 1200 ? "medium" : "large";

Formatted over several lines, one level of chaining is readable enough:

JavaScript
const size =
  width < 600 ? "small" :
  width < 1200 ? "medium" :
  "large";

Go deeper, or nest a ternary inside the first branch, and readers will struggle. At that point, an if...else chain or a function with early returns is clearer.

Don't use the ternary for side effects. isValid ? save() : showError(); works, but it hides two actions inside an expression. When you're doing something rather than choosing a value, write an if...else. Ternaries are for values.

The switch statement

A switch compares one value against a list of case values and jumps to the first match:

JavaScript
switch (expression) {
  case value1:
    // runs when expression === value1
    break;
  case value2:
    // runs when expression === value2
    break;
  default:
    // runs when nothing matched
}

Each comparison uses strict equality (===), so "1" doesn't match 1. The default case is optional and runs when no case matches. And break ends the switch; you'll see why it's needed in a moment.

JS A basic switch

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

No output.

Fallthrough: why break matters

Here's the part that surprises newcomers. A case label is just an entry point. Once switch jumps to a matching case, it runs every statement below it, through the following cases too, until it reaches a break, a return or the end of the switch. This is called fallthrough.

JS Forgetting break

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

No output.

Usually fallthrough is a bug: someone forgot a break. But it has one legitimate, common use: grouping several cases that share the same code. Stack the labels with nothing between them:

JS Grouping cases

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

No output.

Notice that this function uses return instead of break. Inside a function, return leaves the function and therefore the switch, so no break is needed after it.

Mark intentional fallthrough. If you ever let one non-empty case run into the next on purpose, add a comment such as // falls through. Linters recognize it, and so do the humans who read your code later.

Blocks inside cases

All the cases of a switch share one block. So two cases that each declare const total collide with a SyntaxError. Wrap a case's body in its own braces to give it a private scope:

JavaScript
switch (shape.kind) {
  case "circle": {
    const area = Math.PI * shape.radius ** 2;
    return area;
  }
  case "square": {
    const area = shape.side ** 2;
    return area;
  }
}

switch (true) for ranges

Because case values can be any expression, some code uses switch (true) with conditions as cases: case score >= 90:. It works, since the first case that evaluates to true matches, but an if...else if chain says the same thing more directly. Prefer the if chain for ranges.

Lookup objects: often the best choice

Many switch statements do nothing more than map one value to another. An object, or a Map, does that job with less code and no risk of a missing break:

JS A lookup object instead of switch

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

No output.

The ?? operator from Nullish Coalescing and Optional Chaining supplies the default when the key is missing. The lookup object is also data: you can log it, loop over it, or load it from a file, none of which you can do with a switch.

One catch with plain objects: they inherit properties such as toString, so statusColors["toString"] returns a function, not undefined. If the key comes from user input, check with Object.hasOwn(statusColors, key) first, or use a Map, which has no inherited keys.

Which one should you use?

Situation Best tool
Pick one of two values Ternary ? :
Different actions for two or three conditions if...else
Ranges or unrelated conditions (>=, &&) if...else if
One value matched against many fixed options, with different statements per option switch
One value mapped to another value or function Lookup object or Map

None of these is "more advanced" than the others. Pick the one that makes the intent obvious to the next reader.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does const msg = 0 ? "yes" : "no"; store in msg?

    0 is falsy, so the ternary produces the value after the colon, "no".
  2. 2. A switch has case 1: and is given the string "1". What happens?

    switch compares with ===, which never converts types. The string "1" is not strictly equal to the number 1.
  3. 3. What is fallthrough in a switch?

    After a match, switch keeps executing statements below, through later cases, until it meets break, return or the end.
  4. 4. Which is the clearest replacement for a switch that only maps a status string to a color string?

    When each case just maps one value to another, a lookup object (or Map) is shorter, cannot fall through, and is plain data.
  5. 5. When is the ternary operator a poor choice?

    Ternaries are for producing values. For actions with side effects, an if...else statement is clearer.

Summary

  • condition ? a : b is an expression that produces a when the condition is truthy and b otherwise. Use it for values, not actions.
  • Chain ternaries at most one level, formatted over several lines; otherwise use if...else.
  • switch compares one value against case values with strict equality and runs default when nothing matches.
  • Without break or return, execution falls through into later cases. Stack empty cases to group them on purpose.
  • Wrap a case body in braces when it declares variables.
  • When a switch just maps values to values or functions, a lookup object or Map is usually cleaner.

Next: for Loops โ€” repeating code a set number of times.