Skip to the solution
EasyFrontend6 min read

What is the difference between includes and indexOf?

807 views

The problem

Question presented to candidate: "You're checking whether an array contains the value NaN. Would indexOf or includes give you the correct answer, and why does the other one fail?"

What a strong answer should cover:

  • πŸ“Œ Interview term: indexOf(value) β€” returns the value's numeric index in the array (or -1 if not found), comparing elements using strict equality (===) internally.
  • πŸ“Œ Interview term: includes(value) β€” returns a plain boolean, comparing elements using the SameValueZero algorithm, which is identical to === except it correctly treats NaN as equal to itself.
  • πŸ“Œ Interview term: the direct answer to the prompt β€” verified directly: arr.indexOf(NaN) genuinely returns -1 even when NaN is present in the array, because NaN === NaN is false; arr.includes(NaN) genuinely returns true, correctly finding it, because SameValueZero treats NaN as equal to itself.
  • πŸ“Œ Interview term: the classic truthiness pitfall β€” verified directly: if (arr.indexOf(x)) is a real, common bug, because a match at index 0 is falsy, silently causing the if to behave as if no match was found; includes's boolean return type avoids this class of bug entirely.
  • A precise answer names that both methods accept an optional second fromIndex argument with identical start-position semantics, and that str.includes() (on strings) works analogously, with an empty string always reported as included.

Clarifying questions expected:

  • None β€” this is a definitional/comparison question; leading directly with the NaN distinction (since it is the sharpest, most testable difference) is the strong signal.

Code / implementation expected: Yes β€” demonstrating the real NaN contrast directly (indexOf returns -1, includes returns true) is the most convincing proof of understanding.

  • array-methods
  • includes

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

6 min read Β· 8 sections

Run the code

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

JavaScriptReal proof: indexOf can't find NaN, includes can, plus the classic index-0 truthiness bug

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 13 of 165 in JavaScript

Keep your momentum going.

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

Up nextEasy

Describe the concept of 'scope' in JavaScript.

Continue