Is NaN falsy? Why NaN === false returns false
1.Why NaN === false => false, isn't NaN falsy?
The term "falsy" isn't defined in ECMA-262, it's jargon for where type conversion coerces a value to false. e.g.
var x = NaN;
if (!x) {
console.log('x is "falsy"');
}
The strict equality operator uses the Strict Equality Comparison Algorithm which checks that the arguments are of the same Type, and NaN
is Type number, while false
is Type boolean, so they evaluated as not equal based on Type, there is no comparison of value.
2.Why NaN === NaN => false, but !!NaN === !!NaN => true
Because the strict equality comparison algorithm states that NaN !== NaN
, hence the isNaN method.
Using ! coerces the argument to boolean using the abstract ToBoolean method, where !NaN
converts to true and !!NaN
converts to false, so:
!!NaN === !!NaN --> false === false --> true
Note that the abstract equality operator ==
will coerce the arguments to be of the same Type according to the rules for the Abstract Equality Comparison Algorithm. In this case, NaN is Type number, so false is converted to a number using toNumber which returns 0
. And 0
is not equal to NaN so:
NaN == false --> NaN == 0 --> false
This condition:
NaN === false
Is always false
because numbers are not booleans. To test if a value is falsy you can use a ternary expression:
NaN ? "truthy" : "falsy" // falsy
Why NaN === NaN => false
This is explained in MDN; pragmatically speaking, though, two values of which you only know they're not numbers can't logically be the same thing.
... but why is !!NaN === !!NaN => true
This is because casting NaN
into a boolean will make it false
and booleans can be compared as per normal.
- Falsy and being strictly equal to
false
are very different things, that's why one has ay
instead of ane
. ;) NaN
is spec'd to never be equal to anything. The second part of your question is comparingfalse === false
, which is funnily enough,true
:)
If you really want to know if something is NaN
, you can use Object.is()
. Running Object.is(NaN, NaN)
returns true
.