Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a comparison evaluated when it includes NaN in Javascript?

Tags:

javascript

nan

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?

like image 964
qdog Avatar asked May 21 '26 17:05

qdog


2 Answers

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.

...

like image 108
CertainPerformance Avatar answered May 23 '26 06:05

CertainPerformance


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.

like image 45
pwilcox Avatar answered May 23 '26 06:05

pwilcox