I understand the reasoning behind this. I'm curious about the technical implementation. Having trouble finding this somewhere.
My theory is that as soon as the left NaN is evaluated in any comparison, it automatically returns false without performing the comparison at all. Is this correct?
Yes - if both types are the same, and they are numbers, then if the left one is NaN, then the result is false, without checking the value of the right one:
https://www.ecma-international.org/ecma-262/6.0/#sec-strict-equality-comparison
7.2.13 Strict Equality Comparison
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
If Type(x) is different from Type(y), return false.
If Type(x) is Undefined, return true.
If Type(x) is Null, return true.
If Type(x) is Number, then
If x is NaN, return false.
If y is NaN, return false.
If x is the same Number value as y, return true.
If x is +0 and y is −0, return true.
If x is −0 and y is +0, return true.
Return false.
...
Just to clarify a point on the HOW. I was surprised, given @CertainPerformance's (correct) answer, that the code below resulted in the value of "a" being "overwritten".
let a = 'overwrite me';
let x = () => {
a = 'overwritten';
return 7;
}
NaN === x();
alert(a);
But reading the excerpt carefully, I gather that typeof(x()) is called behind the scenes, which would cause the overwriting.
In other words, this is not a short circuit in the fullest sense of the term.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With