Home > Mobile >  Why does a non-default last-case execute in JavaScript switch?
Why does a non-default last-case execute in JavaScript switch?

Time:01-13

I have (ab)used a switch statement like this:

const foo = figureOutWhatFooIs()
console.log(foo) // 'bar'

switch (foo) {
  case 'bar':
    console.log('foo = bar')
  case 'baz':
    console.log('foo = baz')
}

i.e. no break's and no default

I discovered that even when foo = 'bar', the baz case (and incidentally the last case) also executes.

I'm not surprised that the last case was checked but I am surprised that it executed. Thoughts? Thanks!

CodePudding user response:

Checking is done at the start of switch statement, NOT during running case statements.

The case clause works similar to labels and goto/JUMP statements in other languages such as C 1 and Assembly2, which means case 'bar': is nothing more than a label that can be used to "jump" execution to it, but does nothing logical in itself.

So, when a case clause matches, JavaScript "jumps" you to that label, and then runs all statements one by one, ignoring any other case clauses because they're simply labels.

But of course, if there's any break statement along the way, it'll exit switch.

The main reason switch statement does not break by default could be so that it's easier to match multiple conditions like this:

switch (color) {
  case 'red':
  case 'orange':
  case 'blue':
    console.log('Colorful!');
    break;
  case 'black':
  case 'white':
  case 'gray':
    console.log('Black & white!');
    break;
  default:
    console.log('What color is that??');
}

1 https://en.cppreference.com/w/cpp/language/goto

2 https://www.tutorialspoint.com/assembly_programming/assembly_conditions.htm

CodePudding user response:

it is because you are not using break, so after running the first case, is going to continue with the others. Make a test, adding another 2 cases, one before 'bar' case and the second after it. The first one isn't going to run when foo = 'bar' (because is before) but the second is going to run, and if you add more cases after the 'bar' case, every one is going to execute if you don't use break. That's why is very important to use in switch

  • Related