Oleksandr Buchek Oleksandr Buchek - 5 months ago 21
Javascript Question

JS NaN comparison in switch cases

Making a function and can`t understand how would I make a comparison in switch case, so NaN === case goes true and return "Input number is Number.NaN";

function whatNumberIsIt(n){
var str;
switch (n) {
case Number.MAX_VALUE : str = "Input number is Number.MAX_VALUE";
break;
case Number.MIN_VALUE : str = "Input number is Number.MIN_VALUE";
break;
case Number.NaN : str = "Input number is Number.NaN";
break;
case -Infinity : str = "Input number is Number.NEGATIVE_INFINITY";
break;
case Infinity : str = "Input number is Number.POSITIVE_INFINITY";
break;
default : str = "Input number is " + n;
}
return str;
}
whatNumberIsIt(NaN)

Answer

Compare isNaN in the switch statement, check for false. Here's the code:

  function whatNumberIsIt(n){
        var str;

        /**
         * The  !isNaN(n)  here is really the secret sauce.
         * This means the value has to be a real number before comparisons will 
         * even happen. That's why we're able to compare "false" in the switch... otherwise
         * this code wouldn't work.
         */
        switch (!isNaN(n) && n) {
            case Number.MAX_VALUE : 
                str = "Input number is Number.MAX_VALUE";
                break;

            case Number.MIN_VALUE : 
                str = "Input number is Number.MIN_VALUE";
                break;

            case false : 
                str = "Input number is Number.NaN";
                break;

            case -Infinity : 
                str = "Input number is Number.NEGATIVE_INFINITY";
                break;

            case Infinity : 
                str = "Input number is Number.POSITIVE_INFINITY";
                break;

            default : str = "Input number is " + n;
        }

        return str;
      }

  console.log( whatNumberIsIt("String") );
  console.log( whatNumberIsIt(NaN) );
  console.log( whatNumberIsIt(1) );
  console.log( whatNumberIsIt(Infinity) );
  console.log( whatNumberIsIt(-Infinity) );

Fiddle: https://jsfiddle.net/87o83q2q/

Here's the output you should expect:

Input number is Number.NaN
Input number is Number.NaN
Input number is 1
Input number is Number.POSITIVE_INFINITY
Input number is Number.NEGATIVE_INFINITY