Chris
Chris

Reputation: 7310

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

Upvotes: 19

Views: 41370

Answers (4)

EyalAr
EyalAr

Reputation: 3170

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
}

Upvotes: 38

disjunction
disjunction

Reputation: 656

Javascript is type-aware. So '1' is not the same as 1. In your case the "user" has to be numeric, not the string. You can cast it by just:

user = Number(user)

Upvotes: 6

abuduba
abuduba

Reputation: 5042

Cast type of user variable to integer

 switch (+user) {   
    case 1: .. //
 }

Upvotes: 13

mahadeb
mahadeb

Reputation: 676

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

Upvotes: 12

Related Questions