Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 351
sethW Avatar asked Mar 08 '23 01:03

sethW


1 Answers

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

like image 131
Nina Scholz Avatar answered Mar 09 '23 14:03

Nina Scholz