⚡ JavaScript: Fix Array.prototype.includes Returning False for NaN Because a Custom Equality Check Replaced Its Built-In SameValueZero Comparison
Array.prototype.includes is specified to use the SameValueZero algorithm, which is the one built-in piece of JavaScript that actually treats NaN as equal to itself, unlike ===, so [NaN].includes(NaN) correctly returns true with no extra work. Code that replaces a plain .includes() call with a manual .some(x => x === value) check — to add logging, a transform, or a custom comparator — loses that behavior silently, because === never considers NaN equal to anything, including another NaN, so the exact same lookup that worked with .includes() starts returning false the moment it’s rewritten with strict equality.
🔎 The Problem
const seen = [1, 2, NaN, 4]; seen.includes(NaN); // true - Array.prototype.includes uses SameValueZero seen.some(x => x === NaN); // false - === never considers NaN equal to anything, even NaN // Rewriting a lookup from .includes() to a manual .some() check // silently loses NaN handling, with no error anywhere.
✅ Fix: Use Object.is When You Reimplement the Check Yourself
- If you’re replacing
.includes()with a manual search for any reason, useObject.is(a, b)instead of===in the comparator to keep the same NaN-equals-NaN behavior.includes()gave you for free. - Add a unit test with
NaNspecifically present in the collection whenever a lookup function is rewritten from a built-in array method to a custom one, since this is exactly the kind of edge case a normal test suite built around real-world values never happens to exercise. - If the collection can plausibly contain
NaN— parsed numeric input is the most common source — keep using.includes()directly rather than reimplementing the search, since there’s rarely a good reason to give up its NaN handling on purpose.
🚨 Why This Is Dangerous
- A “does this collection contain this value” check that silently stops recognizing
NaNas present can let duplicate or invalidNaNentries slip past a dedup or validation step that used to catch them, with no error anywhere, because the code still runs — it just quietly returns the wrong answer for one specific value.
NaN breaks === before it breaks anything else in your code — .includes() is one of the rare spots where the language already fixed that for you, right up until you rewrite it yourself.
