Skip to content
aviral gupta

// B3.2 · ~30 min · Beginner

switch and the conditional operator

After this lesson you pick one of many fixed values with switch, predict what a missing break does, and choose between cond ? a : b and if for a two-way decision.

Lesson 2 of 5 in B3 Control flow and loops

You will be able to

  • Write a switch with case, break and default, knowing it compares with ===
  • Predict fall-through when a break is missing, and group cases on purpose
  • Write cond ? a : b for a value, and choose it or if for a task
  1. Warm-up · Activity 1 of 7

    Warm-up: which statement is made for choosing between many fixed values of one variable, such as the name of a day?

  2. Predict · Activity 2 of 7

    Predict before you read on: none of the cases has a break. What does this print?

    const size = "M";
    switch (size) {
      case "S":
        console.log("small");
      case "M":
        console.log("medium");
      case "L":
        console.log("large");
    }
  3. Practice · Activity 3 of 7

    Fill in the keyword that ends the case, so that the program prints stop and then done, and never go.

    const light = "red";
    switch (light) {
      case "red":
        console.log("stop");
        ____;
      case "green":
        console.log("go");
    }
    console.log("done");
    ;
  4. Practice · Activity 4 of 7

    The choice comes from a form, as text. What does this print?

    const choice = "2";
    switch (choice) {
      case 1:
        console.log("tea");
        break;
      case 2:
        console.log("coffee");
        break;
      default:
        console.log("unknown");
    }
  5. Practice · Activity 5 of 7

    Match each conditional expression to the value it gives.

  6. Brain teaser · Activity 6 of 7

    Brain teaser. The default is not at the end. What does this print?

    const code = 7;
    switch (code) {
      case 1:
        console.log("one");
        break;
      default:
        console.log("other");
      case 2:
        console.log("two");
        break;
    }
  7. Apply · Activity 7 of 7

    Mini-task. Write a day planner. Store a day as "mon" to "sun" in a constant and use a switch to print Weekend: sleep in for "sat" and "sun" (one grouped case), Almost weekend for "fri", and Workday: alarm at 7 for every other day. Then print how many tasks are left, with task or tasks chosen by the conditional operator. Try several days and task counts.

    Check your work against this list

Build it yourself

Read the worked example, then write the exercises. Your code runs in your browser or on your computer and is never uploaded.

Worked example

A parcel price list

This program prices parcels by size with a switch: L and XL share a case, and an unknown size falls to the default. Then the conditional operator chooses words: parcel or parcels, next day or 3 to 5 days. Run it, then change size to "XL" or "XXL", count to 1 and express to false, and predict each line before you run it again.

main.js

// Price parcels by their size, and describe the order.
const size = "M";
const count = 3;
const express = true;

let price;
switch (size) {
  case "S":
    price = 3;
    break;
  case "M":
    price = 4.5;
    break;
  case "L":
  case "XL":
    price = 9;
    break;
  default:
    price = 0;
    console.log("Unknown size:", size);
}

console.log(`Size ${size}: ${price} EUR each`);
console.log(`${count} ${count === 1 ? "parcel" : "parcels"}`);
console.log("Delivery:", express ? "next day" : "3 to 5 days");
console.log("Total:", count * price, "EUR");

Run it with

node main.js

Output

Size M: 4.5 EUR each
3 parcels
Delivery: next day
Total: 13.5 EUR
  • size is "M", so the switch runs case "M", sets the price and leaves at its break.
  • case "L" has no code of its own: it falls through to the code of case "XL", so both sizes cost 9.
  • count === 1 is false, so ? : gives its second value, "parcels".
  • express is true, so the delivery line gets the value after ?.
Change it and run it

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.

Exercises

Exercise 1 of 2

Fix the drinks menu

The choice arrives from a form as the text "2", and the menu should answer You chose coffee. and then Thank you!. Instead it says Please choose 1, 2 or 3., and once that is fixed it will print every drink below coffee too. Make the switch compare numbers, and stop each case at its end. Keep the cases as numbers.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.

Hints
  1. Hint 1

    switch compares with ===, and "2" === 2 is false. Convert the text with Number() before the switch compares it.

  2. Hint 2

    Once a case matches, the switch runs on into the cases below until it meets a break.

  3. Hint 3

    Add break; as the last line of cases 1, 2 and 3.

Show a solution

One way to solve it. Yours can look different and still pass the checks.

const typed = "2";

switch (Number(typed)) {
  case 1:
    console.log("You chose tea.");
    break;
  case 2:
    console.log("You chose coffee.");
    break;
  case 3:
    console.log("You chose juice.");
    break;
  default:
    console.log("Please choose 1, 2 or 3.");
}
console.log("Thank you!");
Run it on your computer

Install ECMAScript 2026 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.js

const typed = "2";

switch (typed) {
  case 1:
    console.log("You chose tea.");
  case 2:
    console.log("You chose coffee.");
  case 3:
    console.log("You chose juice.");
  default:
    console.log("Please choose 1, 2 or 3.");
}
console.log("Thank you!");

main.test.js

import {test} from 'node:test';
import assert from 'node:assert/strict';
import {runMain} from './learnrun.js';

const lines = async () => (await runMain()).trimEnd().split('\n');

test('the text "2" chooses coffee', async () => {
  const got = await lines();
  assert.equal(got[0], 'You chose coffee.', `the first line is ${JSON.stringify(got[0])}, expected "You chose coffee."`);
});

test('no other drink is printed', async () => {
  const got = await lines();
  assert.deepEqual(got, ['You chose coffee.', 'Thank you!'], `the program printed ${JSON.stringify(got)}`);
});

package.json

{
  "type": "module"
}

package.json tells Node.js that the .js files are modules; keep it in the folder.

Run the program:

node main.js

Run the checks (needs learnrun.js in the same folder):

node --test
Download learnrun.js

Exercise 2 of 2

Words that fit the value

A phone status bar prints 1 messages, Status: false and Battery: 15. Use the conditional operator so that it prints 1 message (messages for any other number), Status: offline (online when online is true), and Battery: low when the battery is below 20 (ok otherwise). Keep the three constants and their values.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.

Hints
  1. Hint 1

    The pattern is condition ? valueIfTrue : valueIfFalse, and it gives a value you can print.

  2. Hint 2

    Inside a template literal: `${messages} ${messages === 1 ? "message" : "messages"}`.

  3. Hint 3

    online is already true or false, so it can be the condition on its own: online ? "online" : "offline".

Show a solution

One way to solve it. Yours can look different and still pass the checks.

const messages = 1;
const online = false;
const battery = 15;

console.log(`${messages} ${messages === 1 ? "message" : "messages"}`);
console.log("Status:", online ? "online" : "offline");
console.log("Battery:", battery < 20 ? "low" : "ok");
Run it on your computer

Install ECMAScript 2026 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.js

const messages = 1;
const online = false;
const battery = 15;

console.log(`${messages} messages`);
console.log("Status:", online);
console.log("Battery:", battery);

main.test.js

import {test} from 'node:test';
import assert from 'node:assert/strict';
import {runMain} from './learnrun.js';

const lines = async () => (await runMain()).trimEnd().split('\n');

test('one message is singular', async () => {
  const got = await lines();
  assert.equal(got[0], '1 message', `the first line is ${JSON.stringify(got[0])}, expected "1 message"`);
});

test('the status is a word', async () => {
  const got = await lines();
  assert.equal(got[1], 'Status: offline', `the second line is ${JSON.stringify(got[1])}, expected "Status: offline"`);
});

test('a battery of 15 is low', async () => {
  const got = await lines();
  assert.equal(got[2], 'Battery: low', `the third line is ${JSON.stringify(got[2])}, expected "Battery: low"`);
});

test('prints exactly three lines', async () => {
  const got = await lines();
  assert.equal(got.length, 3, `the program printed ${got.length} line(s), expected 3`);
});

package.json

{
  "type": "module"
}

package.json tells Node.js that the .js files are modules; keep it in the folder.

Run the program:

node main.js

Run the checks (needs learnrun.js in the same folder):

node --test
Download learnrun.js

Common mistakes

A comparison as a case

const score = 75;
switch (score) {
  case > 50:
    console.log("pass");
    break;
}

What Node.js prints

SyntaxError: Unexpected token '>'

Why, and the fix

A case holds one value, which the switch compares with ===; it is not a condition. case > 50: cannot be read, so no line of the file runs. For ranges, write an if chain: if (score > 50) { … } else { … }.

The same let in two cases

const size = "S";
switch (size) {
  case "S":
    let label = "small";
    console.log(label);
    break;
  case "L":
    let label = "large";
    console.log(label);
    break;
}

What Node.js prints

SyntaxError: Identifier 'label' has already been declared

Why, and the fix

All cases of a switch share one block, the braces of the switch, so the second let label declares the same name twice in it. Give each case its own block with braces, case "S": { let label = "small"; … break; }, or declare the variable once above the switch.

A conditional operator without its colon

const online = true;
const label = online ? "online";
console.log(label);

What Node.js prints

SyntaxError: Unexpected token ';'

Why, and the fix

The conditional operator always has three parts: a value for a truthy condition after ?, and one for a falsy condition after :. Without the : part the line cannot be read. Write online ? "online" : "offline". If there is nothing to do in the other case, use an if instead.

JavaScript in the browser: your browser’s own engine, in a sandboxed worker. Syntax errors are located with acorn 8.18.0, MIT. Licence and source

Exit ticket

5 questions, no hints. Score 80% or more to complete the lesson.

Finish every activity above to unlock the exit ticket.

Report a problem

Spotted something wrong or unclear? Say what, and it will be checked and fixed.

#

At least 20 characters.

Only if you want a reply.

Key ideas

switch compares one value with ===

switch (day) { case "sat": … break; default: … } works out day once, then looks for the first case whose value is strictly equal to it, with ===, and runs from there. Nothing is converted: switch ("1") never matches case 1. If no case matches, the default clause runs; without a default, nothing in the switch runs and the program carries on after it. Each case holds one value, not a test: case > 50: is a SyntaxError. For ranges, such as points above 50, use if and else if.

Without break, it falls through

A case is only an entry point. Once a case matches, JavaScript runs every statement after it, through the cases below, until it meets a break or the end of the switch. This is called fall-through. Forget a break and the next case runs as well, whatever its value, and that includes the default. Used on purpose, it groups values: case "sat": case "sun": console.log("weekend"); break; runs one line for both. End every case with break, the last one too, so that adding a case later is safe.

cond ? a : b chooses a value

The conditional operator is the only one with three parts: condition ? valueIfTruthy : valueIfFalsy. It is an expression, so its result can go straight into a const, a console.log or a template literal: const word = count === 1 ? "item" : "items";. Use it when both branches give a value for the same place. Use if when the branches do things, such as printing several lines, or when there are more than two cases. You can chain it, a ? b : c ? d : e, but an else if chain is easier to read.

Sources

Last reviewed October 1, 2026