Skip to content Skip to sidebar Skip to footer

IsNaN(1) And IsNaN("1") Returns False

Why in my screenshot below isNaN(1) and isNaN('1') returns false? As one of them is number and one of them is a string so isNaN('1') should return true.

Solution 1:

From MDN:

When the argument to the isNaN function is not of type Number, the value is first coerced to a Number. The resulting value is then tested to determine whether it is NaN. Thus for non-numbers that when coerced to numeric type result in a valid non-NaN numeric value (notably the empty string and boolean primitives, which when coerced give numeric values zero or one), the "false" returned value may be unexpected; the empty string, for example, is surely "not a number."

The article also suggests using the (experiemental) Number.isNaN function if you don't want this behavior:

console.log(Number.isNaN("1")) // false
console.log(Number.isNaN(NaN)) // true

Or more simply:

console.log("1" != "1") // false
console.log(NaN != NaN) // true

But if what you really want to simply determine if a value of type Number (and not for example, of type String), simply use typeof:

console.log(typeof "1" == "number") // false
console.log(typeof 1 == "number")   // true

But this will return true for NaN because despite being known as 'not a number', it's actually a value of type Number. If you want to ensure that the value is of type Number, and a valid, finite number use the (experimental) Number.isFinite:

console.log(Number.isFinite("1")) // false
console.log(Number.isFinite(1))   // true
console.log(Number.isFinite(NaN)) // false

Or simply create your own:

function myIsFinite(x) { return typeof x == "number" && isFinite(x); }
console.log(myIsFinite("1")) // false
console.log(myIsFinite(1))   // true
console.log(myIsFinite(NaN)) // false

Solution 2:

The isNaN function will convert the input to a number first and then determine if the resulting number is NaN.


Post a Comment for "IsNaN(1) And IsNaN("1") Returns False"