sethW
sethW

Reputation: 185

switch(true) vs. if(true) doesn't return the same (JavaScript)

I'm writing a function for when a button is clicked. There are plenty of different buttons, so I'd like to use a switch(true) statement as opposed to a long series of if...else if statements.

Several of the buttons are for numbers and I've put the number in the value attribute of the <button> tag. However, testing these two functions gives different results.

switch(true) {
    case (Number(button.value)):
        console.log('thats a number');
        break;
    default:
        console.log('NaN');
        break;
}

if(Number(button.value)) {
    console.log('thats a number');
} else {
    console.log('NaN');
}

Can someone please explain why? I've tested thoroughly without getting anywhere and feel like it must be some technical difference in the way switch and if statements are processed.

Upvotes: 4

Views: 624

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386519

The switch statement checks the given condition with strict equality ===, whereas if takes a value which is converted to boolean for a check.

What you get in switch is

true === Number(button.value)

and that check is never true

Upvotes: 7

Related Questions