How do you have a NaN case in a switch statement?

Viewed 6416

Since NaN === NaN evaluates to false, is it possible to add a NaN case to a switch statement?

For example, let's say I want to make the following switch:

switch(x){
    case 1:
    case 2:
    case 4:
        doSomething();
        break;
    case NaN:
        doSomethingElse();
        break;
    case default:
        doADifferentThing();
        break;
}

Sending NaN as x will go to the default case. I know there are ways around using NaN in switch statements (e.g. I can surround with an if..else statement and use isNaN), but is there a more direct approach?

4 Answers

use toString():

switch (x.toString()) {
    case '1':
    case '2':
    case '4':
        console.log('1/2/4');
        break;
    case 'NaN':
        console.log('NaN');
        break;
    default:
        console.log('default');
}
Related