I have a switch case statement that doesn't work. I've checked the input, it's valid. If user is 1, it goes to default. If user is any number, it defaults. What's wrong here? I don't know javascript well at all.
switch (user) {
case 1:
// stuff
break;
case 2:
// more stuff
break;
default:
// this gets called
break;
}
The switch statement executes a block of code depending on different cases. The switch statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions. Use switch to select one of many blocks of code to be executed.
Description. A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict comparison, === ) and transfers control to that clause, executing all statements following that clause.
The reason given against adding switch(String) is that it wouldn't meet the performance guarantees expects from switch() statements. They didn't want to "mislead" developers.
In a switch statement, we pass a variable holding a value in the statement. If the condition is matching to the value, the code under the condition is executed. The condition is represented by a keyword case, followed by the value which can be a character or an integer. After this, there is a colon.
Make sure you are not mixing strings and integers.
Try:
switch (user) {
case "1":
// stuff
break;
case "2":
// more stuff
break;
default:
// this gets called
}
Problem is data type mismatch. cast type of user to integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With