Search code examples
javascriptnan

Why does Number.isNaN() return false for Strings?


As per my understanding NaN stands for Not A Number. Strings are not definitely Numbers and hence I expect the below code to return true for Strings. However, it's not the case.

console.log(Number.isNaN("Stack Overflow"));

Could somebody please clarify this?


Solution

  • There is a distinction to be made between Number.isNaN and isNaN

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN

    The isNaN() function determines whether a value is NaN or not.

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN

    The Number.isNaN() method determines whether the passed value is NaN and its type is Number. It is a more robust version of the original, global isNaN().

    The reason you are returning false is that "Stack Overflow" is not a number it is a string.

    console.log('Number.isNaN("Stack Overflow"): '+Number.isNaN("Stack Overflow"));
    console.log('isNaN("Stack Overflow"): '+isNaN("Stack Overflow"));