Emmanuel Akinfulubi

JavaScriptBasic

Switch statement fallthrough in JavaScript

Intermediate · 3 min read

A switch statement compares one value against a list of cases and runs the code for the one that matches. It's a tidy way to turn a tier name into a fare, or a menu choice into an action. It also has a behavior that surprises almost everyone the first time: once a case matches, JavaScript keeps running into the cases below it until something stops it. That is called fallthrough.

In this tutorial you will map a fare tier to an amount with a switch, use fallthrough on purpose so two tiers share one answer, and then leave out the breaks to see it go wrong. You will also check what a string '1' matches. You need to know how functions, return and === work.

How a switch runs

JavaScript

const day = 'sat';
switch (day) {
  case 'sat':
  case 'sun':
    console.log('weekend'); // weekend
    break;
  default:
    console.log('weekday');
}

JavaScript compares day with each case from the top. At the first match, it jumps there and runs every line from that point down, across later case labels, until it meets a break, a return, or the end of the switch. The labels are only entry points, not walls.

default is where it jumps when no case matches.

Two ways to stop

break leaves the switch and carries on after it. return leaves the whole function. Inside a function that just picks a value, return from each case is the simplest, because there is nothing left to forget.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

97 switch, deliberate fallthrough and the missing break

fair

Map a fare tier to an amount with a switch, letting two tiers share one case. Then write the same switch with the breaks left out, and check what a '1' matches.

Stuck? Three hints, smallest first
  1. 1. Two case labels stacked with no code between them share the body below.
  2. 2. Without break or return, execution runs on into the next case.
  3. 3. switch matches with ===, so no conversion happens.

Step 1: a switch that returns

Fares are in kobo (100 kobo make one naira). The underscore in 500_00 only makes it easier to read.

Step 1

function fareBand(tier) {
  switch (tier) {
    case 'standard':
      return 350_00;
    case 'economy':
      return 200_00;
    default:
      return null;
  }
}
console.log(fareBand('standard')); // 35000
console.log(fareBand('danfo'));    // null

Each case returns, so nothing can run on into the next one. An unknown tier reaches default and gets null.

Step 2: deliberate fallthrough

Luxury and executive cost the same. Stack their labels with nothing between them:

Step 2

function fareBand(tier) {
  switch (tier) {
    case 'luxury':
    case 'executive':
      return 500_00;
    case 'standard':
      return 350_00;
    case 'economy':
      return 200_00;
    default:
      return null;
  }
}
console.log(fareBand('luxury'));    // 50000
console.log(fareBand('executive')); // 50000

'luxury' matches the first label, there is no code under it, so it falls through to the return below 'executive'. Two values, one answer. This is the good kind of fallthrough, and it's the clean way to group cases.

Step 3: the missing break

Now write it the other common way, assigning a variable in each case, and forget the breaks:

Step 3

function leaky(tier) {
  let fare = 0;
  switch (tier) {
    case 'luxury':
      fare = 500_00;
    case 'standard':
      fare = 350_00;
    case 'economy':
      fare = 200_00;
  }
  return fare;
}
console.log(['luxury', 'standard', 'economy'].map(leaky)); // [ 20000, 20000, 20000 ]

Every tier costs ₦200. For 'luxury', JavaScript jumps to the first case, sets 500_00, then runs straight on, setting 350_00 and then 200_00. The last assignment wins. No error, and 'economy' looks right, so a quick test might even pass.

Step 4: put the breaks back

Step 4

function fixed(tier) {
  let fare = 0;
  switch (tier) {
    case 'luxury':
      fare = 500_00;
      break;
    case 'standard':
      fare = 350_00;
      break;
    case 'economy':
      fare = 200_00;
      break;
  }
  return fare;
}
console.log(['luxury', 'standard', 'economy'].map(fixed)); // [ 50000, 35000, 20000 ]

That works, but every break is a line you can forget. When a switch just picks a value, prefer return as in Step 2.

Step 5: switch compares with ===

Step 5

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

switch uses strict equality, ===, so the text '1' is not the number 1. Values from a form or a web address are always text, so convert first: match(Number(input)).

Step 6: where default goes

Step 6

function defaultFirst(tier) {
  switch (tier) {
    default:
      return 'none';
    case 'luxury':
      return 'top';
  }
}
console.log(defaultFirst('luxury')); // top
console.log(defaultFirst('danfo'));  // none

default is only used when no case matches, wherever it is written. Writing it last is still the kind thing to do for whoever reads the code next.

The full solution

The answer panel has fareBand with the stacked cases, the leaky version with no breaks, the '1' versus 1 check, and a switch with default written first. Press Run to see the output.

The answer

function fareBand(tier) {
  switch (tier) {
    case 'luxury':
    case 'executive':          // deliberate: both fall into the line below
      return 500_00;
    case 'standard':
      return 350_00;
    case 'economy':
      return 200_00;
    default:
      return null;
  }
}

// The same ladder with assignments and no breaks. Every match runs to the bottom.
function leaky(tier) {
  let fare = 0;
  switch (tier) {
    case 'luxury':
      fare = 500_00;
    case 'standard':
      fare = 350_00;
    case 'economy':
      fare = 200_00;
  }
  return fare;
}

function match(value) {
  switch (value) {
    case 1:
      return 'number one';
    default:
      return 'no match';
  }
}

// default is chosen only when no case matches, wherever it is written.
function defaultFirst(tier) {
  switch (tier) {
    default:
      return 'none';
    case 'luxury':
      return 'top';
  }
}

console.log('leaky:', ['luxury', 'standard', 'economy'].map(leaky));
console.log('switch on a string 1:', match('1'));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a stacked case is a deliberate fallthrough', fareBand('executive'), 50000);
test('and the plain case beneath it', fareBand('standard'), 35000);
test('an unknown tier reaches default', fareBand('danfo'), null);
test('a missing break falls into the next case', leaky('luxury'), 20000);
test('which is only visible at the bottom of the ladder', leaky('standard'), 20000);
test('the last case has nothing left to fall into', leaky('economy'), 20000);
test('switch compares with ===, so the string 1 is not the number 1', match('1'), 'no match');
test('the number matches', match(1), 'number one');
test('default runs last even when it is written first', defaultFirst('danfo'), 'none');

Fallthrough is a feature and a hazard in the same mechanism. Stacking case 'luxury': case 'executive': with nothing between them is the clean way to give two values one answer. Forgetting a break gives you leaky, where every tier returns ₦200 because control ran through every remaining case — and the compiler is happy, because that is exactly what switch is defined to do.

Returning from each case, as fareBand does, makes the whole class of bug impossible and is the shape to prefer. Two smaller points: switch matches with ===, so a form field's '1' will never hit case 1 — convert first; and default is chosen only when nothing else matched, no matter where it appears, though writing it last is a kindness to the reader. For anything that is purely value-to-value, a lookup table (exercise 87) is shorter than either.

Common mistakes

  • Forgetting break. The matching case runs on into the next ones, and the last assignment wins.
  • Switching on a form value without converting it. '1' never matches case 1.
  • Leaving out default. An unknown value then silently does nothing. Return or log something.

Try it yourself

  1. Add a 'shuttle' tier that costs 0, and check fareBand('shuttle') gives 0.
  2. Write daysIn(month) with a switch where 'apr', 'jun', 'sep' and 'nov' share one return 30.
  3. Rewrite fareBand as a lookup table: { luxury: 500_00, executive: 500_00, ... }.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.