Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this JavaScript includes() feature make sense? [duplicate]

I'm learning about includes() feature, and I found this code

[NaN].includes(NaN) //True

But

NaN === NaN // False

Why this is posible?

like image 834
Jonatan Santa Cruz Avatar asked Jun 18 '26 15:06

Jonatan Santa Cruz


1 Answers

Using equality NaN === NaN and using includes [NaN].includes(NaN) are basically asking two different questions:

  1. Equality - are this things that have the same name are actually equal?

NaN is an amorphic entity, which describes the concept of not being a numeric value, and doesn't actually have a value you can compare. Equality uses the Strict Equality Comparison, and defines that a comparison x === y with NaN on any side of the equation is always false:

a. If x is NaN, return false.
b. If y is NaN, return false.

  1. Includes - do I have something with that "name" in the array?

However, to search for a NaN in an array, and to keep the to Array#includes signature of passing only one param, and not a callback, we need a way to "name" what we are searching for. To make that possible, ccording to the Array#includes definition in the ECMAScript 2016 (ECMA-262) docs:

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 treating them as undefined.

The definition of SameValueZero(x, y) states that when comparing:

If x is NaN and y is NaN, return true.

like image 120
Ori Drori Avatar answered Jun 21 '26 05:06

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!