whatstheoutput_

#56: indexOf(NaN) vs includes(NaN)

Topic: arrays · Difficulty: ★★

const arr = [1, NaN, 3];
console.log(arr.indexOf(NaN));
console.log(arr.includes(NaN));

Output

-1
true

Why

Array.prototype.indexOf() finds elements using strict equality (===) under the hood, and NaN is the one value in JavaScript that is never strictly equal to itself (NaN === NaN is false) — so indexOf can NEVER find a NaN in an array, always returning -1 regardless of whether one is present. includes() was deliberately specified to use the SameValueZero algorithm instead, which treats NaN as equal to NaN, so it correctly reports true. This asymmetry is the main reason includes() exists at all — it fixes indexOf's blind spot for NaN.

More arrays puzzles

Play today's puzzle →