Skip to the solution
MediumDSA5 min read

Implement Array.prototype.includes() Handling NaN Correctly

1.1k views

The problem

Problem, as an interviewer would state it: "Implement Array.prototype.myIncludes from scratch — and explain, with real proof, exactly why it exists as a SEPARATE method from indexOf, rather than callers just checking indexOf(x) !== -1."

Examples:

Code
[1, NaN, 3].includes(NaN); // true
[1, NaN, 3].indexOf(NaN);  // -1 -- genuinely, permanently cannot find it

Clarifying questions expected:

  • What comparison algorithm does includes() genuinely use internally — is it the same strict equality (===) that indexOf uses?
  • Does includes() need to support a negative fromIndex, counting back from the end?
  • Does +0 and -0 need to be treated as equal, matching real native includes()'s documented behavior?

Code / implementation expected: Yes — real, direct proof that includes() finds a real NaN while indexOf genuinely cannot, PLUS proof of negative fromIndex and +0/-0 handling, both matching real native includes exactly.

  • polyfill
  • array
  • edge-cases

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: includes() finds a real NaN via SameValueZero, while real native indexOf genuinely, permanently cannot find it via strict equality

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 86 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Async map limit concurrency

Continue