I'm familiar with NaN being "weird" in JavaScript, i.e., NaN === NaN always returns false, as described here. So one should not make === comparisons to check for NaN, but use isNaN(..) instead.
So I was surprised to discover that
> [NaN].includes(NaN)
true
This seems inconsistent. Why have this behavior?
How does it even work? Does the includes method specifically check isNaN?
As you can see reading include documentation, it does use the sameValueZero algorithm to work, so as its documentation say, it gives a True value when comparing NaN and I quote:
We can see from the sameness comparisons table below that this is due to the way that
Object.ishandles NaN. Notice that if Object.is(NaN, NaN) evaluated to false, we could say that it fits on the loose/strict spectrum as an even stricter form of triple equals, one that distinguishes between -0 and +0. The NaN handling means this is untrue, however. Unfortunately,Object.ishas to be thought of in terms of its specific characteristics, rather than its looseness or strictness with regard to the equality operators.
The .includes() method uses SameValueZero algorithm for checking the equality of two values and it considers the NaN value to be equal to itself.
The SameValueZero algorithm is similar to SameValue, but the only difference is that the SameValueZero algorithm considers +0 and -0 to be equal.
The Object.is() method uses SameValue and it returns true for NaN.
console.log(Object.is(NaN, NaN));
The behavior of .includes() method is slightly different from the .indexOf() method; the .indexOf() method uses strict equality comparison to compare values and strict equality comparison doesn't consider NaN to be equal to itself.
console.log([NaN].indexOf(NaN));
Information about different equality checking algorithms can be found at MDN:
In 7.2.16 Strict Equality Comparison, there is the following note:
NOTE
This algorithm differs from the SameValue Algorithm in its treatment of signed zeroes and NaNs.
This means for Array#includes a different comparison function than for a strict comparison:
22.1.3.13 Array.prototype.includes under
NOTE 3
The includes method intentionally differs from the similar indexOf method in two ways. First, it uses the SameValueZero algorithm, instead of Strict Equality Comparison, allowing it to detect NaN array elements. Second, it does not skip missing array elements, instead of treating them as undefined.
According to MDN's document say that
Note: Technically speaking,
includes()uses thesameValueZeroalgorithm to determine whether the given element is found.
const x = NaN, y = NaN;
console.log(x == y); // false -> using ‘loose’ equality
console.log(x === y); // false -> using ‘strict’ equality
console.log([x].indexOf(y)); // -1 (false) -> using ‘strict’ equality
console.log(Object.is(x, y)); // true -> using ‘Same-value’ equality
console.log([x].includes(y)); // true -> using ‘Same-value-zero’ equality
Object.is() and === is in their treatment of signed zeroes and NaNs.