Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS switch case not working

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;
}
like image 725
Chris Avatar asked Jun 22 '12 08:06

Chris


People also ask

Does JavaScript support switch case?

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.

How does switch case work in JavaScript?

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.

Why can't you use a switch () statement on strings?

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.

How do you check the condition of a switch case?

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.


2 Answers

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
}
like image 196
EyalAr Avatar answered Sep 21 '22 21:09

EyalAr


Problem is data type mismatch. cast type of user to integer.

like image 29
mahadeb Avatar answered Sep 22 '22 21:09

mahadeb