Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Every case in switch is triggered in JS

Tags:

javascript

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!

like image 369
Kubaghetto the fresh Testobun Avatar asked Nov 15 '25 17:11

Kubaghetto the fresh Testobun


1 Answers

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;.

like image 108
Akash Kava Avatar answered Nov 18 '25 07:11

Akash Kava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!