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!

1 Answers1

2

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 - Krabbe mit Hüten
  • 24,143
  • 12
  • 85
  • 121
Akash Kava
  • 37,943
  • 20
  • 116
  • 165