9

I have the following switch simple case:

let ca: string = "2";

switch (ca) {
case "2":
    console.log("2");

 case "1":
    console.log("1");

default:
    console.log("default");

}

I'm trying to understand why the output of this code is:

2
1
default

My expected output is

2 default

why its print

1

even if ca isn't equal "1"?

EDIT: I know that I can add break statment - I just trying to understand why case "1" occurred if ca="2"

Thanks.

samisaviv
  • 283
  • 1
  • 7
  • 17
  • Useful reading that will clear some of your confusion: https://stackoverflow.com/questions/188461/switch-statement-fallthrough-should-it-be-allowed – byxor Jan 30 '20 at 14:14

2 Answers2

23

You need to add a break statement in each of the case you have for the switch block otherwise it will keep executing further once the match is found.

let ca: string = "2";

switch (ca) {
  case "2":
    console.log("2");
    break;

  case "1":
    console.log("1");
    break;

  default:
    console.log("default");
}
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • I know that, I'm trying to understand why case "1" occured even in ca="2" – samisaviv Jan 30 '20 at 13:59
  • 1
    @samisaviv that's how `switch` works. It starts with the specific `case` and runs all the cases below it if you don't add `break`. If you set `ca = "1"`, it runs `case "1"` AND `default` – adiga Jan 30 '20 at 14:08
  • If your question is why was ``switch`` with falls through strategy, I guess it is to give the possibility to make an "OR" with the switch e.g. ``` switch (ca) { case "2": case "1": console.log("smaller than 3"); break; } ``` – JB Cha Apr 21 '21 at 12:53
1

The switch statement in JavaScript falls through to the next case until a break statement is hit:

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.

TypeScript is no different in this regard. It's an unfortunate holdover from the C language, or maybe even older.

I recommend you enable the compiler option --noFallthroughCasesInSwitch so the compiler will prevent the common mistake of forgetting the break statement.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • Manipulating the compiler isn't a solution to misunderstanding a fundamental. – Azeroth2b Aug 27 '21 at 18:09
  • 1
    Indeed it's not, but I believe I addressed the misunderstanding as well. The last sentence was just me trying to be helpful for OP and future readers. – Thomas Aug 28 '21 at 08:13