Skip to solution
easyFrontend

What is the difference between includes and indexOf?

807 views
01

Understand 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-methodsincludes
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Target Audience: Engineers preparing for JavaScript fundamentals interviews. Difficulty: Easy

How to read this doc: Concepts are explained in plain language first, then tagged with 📌 Interview term:. Every comparison below, including the NaN case, was actually run in Node.

1. Why This E

Solution ready — 2 min read

Classified // press E to declassify

04

Run the code

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

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 13 of 165 decoded in the JavaScript track. One more won't hurt.

Back to track