2

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?

qdog
  • 151
  • 1
  • 9
  • It's implemented per IEEE 754: https://stackoverflow.com/questions/1565164/what-is-the-rationale-for-all-comparisons-returning-false-for-ieee754-nan-values –  Nov 07 '18 at 21:48
  • @MichaelJasper OP is *specifically* asking *how* the logic is implemented, not *why* - "What is the rationale" is about "why", not "how". – CertainPerformance Nov 07 '18 at 21:54
  • 1
    I was looking more for the accepted answer, which shows the evaluation step by step from start to finish. – qdog Nov 07 '18 at 21:57

2 Answers2

8

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.

...

Community
  • 1
  • 1
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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.

pwilcox
  • 5,542
  • 1
  • 19
  • 31
  • 2
    Both sides need to be evaluated to a *single value* before the `===` check can start, so that the type comparison can be meaningful (and the type comparison with `===` must be done before anything else, even before the `If Type(x) is Number, then...` part). So, your `x` function *has* to be called, so that the right side evaluates to a single value, before the `===` check can happen. – CertainPerformance Nov 07 '18 at 22:19
  • @CertainPerformance. If you're saying that it's not just about "NaN", but for any comparison, then it seems you're right. I replaced "NaN" above with 4, and "a" was overwritten just the same. I did something analogous with string comparisons, and again, overwritten. Good to know. – pwilcox Nov 08 '18 at 23:05