-3

Considering below JS snippet. It prints 1 and 2 both even if case: 2 is not a match! I know, I can put a break; to prevent this, but I want to understand the real logic behind this. As this doesn't make sense to execute a block when there is no match.

var a = 1
switch(a){
    case 1:
  console.log(1)
    case 2:
  console.log(2)
}
Mahesh Thumar
  • 4,257
  • 5
  • 22
  • 30
  • 4
    no [`break`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break) ... means no break. – Nina Scholz Apr 19 '17 at 12:07
  • 4
    `switch` uses a *fall-through* logic; it starts executing everything starting at the first matching case. How useful that is is debatable, but that's the way it's been designed since forever in many languages. – deceze Apr 19 '17 at 12:09
  • 3
    consider if you wanted multiple cases to do the same code block ... – Jaromanda X Apr 19 '17 at 12:09
  • this [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) shows what I mean quite eloquently – Jaromanda X Apr 19 '17 at 12:12

1 Answers1

4

The Switch case statement works like a goto. That means that if you match with a label, you jump directly to it. Your code flow is not affected after it.

Titouan56
  • 6,932
  • 11
  • 37
  • 61
  • That's a neat way of putting it. Kind of a "well-controlled" goto. – Niet the Dark Absol Apr 19 '17 at 12:10
  • IIRC originally it jumped to the matching memory address and then simply executed everything therein; which means every line of code after the matching `case`. Today this probably doesn't have a whole lot of relevance anymore, but the behaviour still stays. – deceze Apr 19 '17 at 12:13