1

I have a little problem to solve a bug in my code regarding to switch case statements.

testvalue = 1

switch(testvalue){
                case 1:
                    console.log("Case 1 loaded");
                case 2:
                    console.log("Case 2 loaded");
                case 3: 
                    console.log("Case 3 loaded");
                case 4: 
                    console.log("Case 4 loaded");
                case 5:
                    console.log("Case 5 loaded");
                default:
                    console.log("Default case loaded");
            }

After I run this part of code, I get the following result in the console:

"Case 1 loaded" "Case 2 loaded" "Case 3 loaded" "Case 4 loaded" "Case 5 loaded" "Default case loaded"

I dont understand why JavaScript is going into every case I have even tho I have 1 as my testvalue and none of the other cases after the first one should be triggered. Is it because testvalue is getting treated as a boolean? When I apply "typeof" to testvalue I get "number" as a result so JS should know that this is not a boolean.

I hope this one is pretty easy to solve. Thats for any kind of help!

  • please put `break;` after every case except default. – endrcn Dec 26 '20 at 10:40
  • 1
    Does this answer your question? [Switch statement multiple cases in JavaScript](https://stackoverflow.com/questions/13207927/switch-statement-multiple-cases-in-javascript) – Tim Biegeleisen Dec 26 '20 at 10:41
  • Does this answer your question? [Why was the switch statement designed to need a break?](https://stackoverflow.com/questions/252489/why-was-the-switch-statement-designed-to-need-a-break) – E_net4 Dec 26 '20 at 11:30
  • Its a nice additional info I just checked out, thank you for the information! – Kubaghetto the fresh Testobun Dec 26 '20 at 14:05
  • Does this answer your question? [In a switch statement, why are all the cases being executed?](https://stackoverflow.com/questions/8058995/in-a-switch-statement-why-are-all-the-cases-being-executed) – SuperStormer Sep 01 '22 at 19:09

1 Answers1

3

JavaScript supports C style switch case fall through, which means unless there is a break specified, it will continue to execute all the subsequent cases.

In order to execute only one set of statements in a case block, you must end it with break;.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Akash Kava
  • 39,066
  • 20
  • 121
  • 167