← Back to JavaScript, page 3

javascript-0055 · Easy fresher

How does the switch statement work in JavaScript, and what are labeled break and continue?

switch compares one value against each case using strict equality and, once a case matches, keeps running every following case until a break, return, or the end. This fallthrough is useful when cases share code and a common bug when break is forgotten. A label lets break or continue target an outer loop instead of only the innermost one.

Full answer

A switch evaluates its expression once and compares the result with each case value using ===. The string '1' does not match the number 1. When a case matches, execution starts there and continues into the next case bodies even when their values do not match. This behavior is called fallthrough. Add break (or return inside a function) to leave the switch. The default branch runs when nothing matches, and it can appear anywhere, but it is conventional to put it last.

Fallthrough is sometimes intended: case 'sat': case 'sun': return 'weekend'; groups several values on one result. Otherwise a missing break is a bug, and many linters warn about it. Each case shares one block scope, so declaring let in two cases with the same name clashes. Wrap case bodies in braces when they declare variables.

A common alternative is an object lookup, such as const messages = { 404: 'Not found' }, or a Map, which is shorter when each case only returns a value. Use switch when cases run statements.

A label is a name placed before a statement, such as outer: for (...). Inside nested loops, break outer leaves the labeled loop completely, and continue outer jumps to its next iteration. Without a label, break and continue apply only to the innermost loop. Labels are rare in everyday code, but they are cleaner than extra flag variables in a search over a grid. A function with return is often cleaner still.

javascript
function dayType(day) {
  switch (day) {
    case 'sat':
    case 'sun':
      return 'weekend';
    case 'fri':
      console.log('fri: runs, then falls through');
    case 'thu':
      return 'almost weekend';
    default:
      return 'weekday';
  }
}
console.log(dayType('sun'), dayType('fri'), dayType('mon'));

function strictCheck(value) {
  switch (value) {
    case 1:
      return 'number one';
    default:
      return 'no strict match';
  }
}
console.log(strictCheck(1), strictCheck('1'));

function describe(code) {
  switch (code) {
    case 200: {
      const text = 'OK';
      return text;
    }
    case 404: {
      const text = 'Not found';
      return text;
    }
    default:
      return 'Unknown';
  }
}
console.log(describe(200), describe(404), describe(500));

const messages = new Map([[200, 'OK'], [404, 'Not found']]);
console.log(messages.get(404) ?? 'Unknown');

const seats = [
  ['free', 'taken', 'free'],
  ['taken', 'free', 'free'],
];
let firstFree = null;
search: for (let row = 0; row < seats.length; row++) {
  for (let col = 0; col < seats[row].length; col++) {
    if (seats[row][col] === 'taken') continue; // next column
    firstFree = [row, col];
    break search; // leaves both loops
  }
}
console.log(firstFree);

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) continue outer;
    console.log('i,j =', i, j);
  }
}

Run with Node.js v24.22.1 as js-55.js; two runs gave identical output. Output: fri: runs, then falls through weekend almost weekend weekday number one no strict match OK Not found Unknown Not found [ 0, 0 ] i,j = 0 0 i,j = 1 0 i,j = 2 0

Key points

  • switch uses strict equality (===).
  • Without break, execution falls through into the next case.
  • Case bodies share one scope; use braces around cases that declare variables.
  • An object or Map lookup replaces a switch that only returns values.
  • break label and continue label control an outer loop.

Common mistakes

  • Forgetting break and running several cases by accident.
  • Expecting switch to compare with loose equality.
  • Declaring the same let name in two cases without braces.
  • Using labels when a function with return is clearer.

Follow-ups

  • How would you use switch (true) with conditions, and is it a good idea?
  • Where does a default placed in the middle run?
  • When would you replace a switch with polymorphism or a lookup table?

Tips

  • Mention strict equality and fallthrough first; they are the two facts interviewers look for.
  • Show the grid search with a label as the one realistic use.
  • Offer the Map lookup as a cleaner replacement when cases only return values.