In Javascript, if we multiply a string with number we get NaN
:
console.log("manas" * 5); // result is NaN
Why then does the following code result in false
instead of true
?
console.log("manas" * 5 == NaN) // results false
In Javascript, if we multiply a string with number we get NaN
:
console.log("manas" * 5); // result is NaN
Why then does the following code result in false
instead of true
?
console.log("manas" * 5 == NaN) // results false
Use the isNaN
function instead.
console.log(isNaN("manas" * 5));
http://www.w3schools.com/jsref/jsref_isnan.asp
NaN, not a number, is a special type value used to denote an unrepresentable value. With JavaScript, NaN can cause some confusion, starting from its typeof and all to the way the comparison is handled.
Several operations can lead to NaN as the result. Because there are many ways to represent a NaN, it makes sense that one NaN will not be equal to another NaN.
NaN
is a special numeric value which is not equal to anything including itself. To properly test for NaN
you need to use isNaN function.
From specification:
Returns true if the argument coerces to NaN, and otherwise returns false.
Here is also useful note from the same ECMAScript section:
A reliable way for ECMAScript code to test if a value X is a NaN is an expression of the form
X !== X
. The result will be true if and only if X is a NaN.
NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself. Testing against NaN
Javascript is not that smart - when either side of the ==
operator is Nan
, the whole thing evaluates as false (similar to how if leftside of ||
is false
, it doesn't bother looking at right side)
So, even Nan == Nan
will return false.
Here's a good article on Nan behaviour
http://ariya.ofilabs.com/2014/05/the-curious-case-of-javascript-nan.html
In Javascript,
NaN == NaN //always results false.
(self comparison of NaN to itself is always false in javascript)
refer:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
also see Is NaN equal to NaN?