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-1if 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 treatsNaNas equal to itself. - 📌 Interview term: the direct answer to the prompt — verified directly:
arr.indexOf(NaN)genuinely returns-1even whenNaNis present in the array, becauseNaN === NaNisfalse;arr.includes(NaN)genuinely returnstrue, correctly finding it, because SameValueZero treatsNaNas equal to itself. - 📌 Interview term: the classic truthiness pitfall — verified directly:
if (arr.indexOf(x))is a real, common bug, because a match at index0is falsy, silently causing theifto 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
fromIndexargument with identical start-position semantics, and thatstr.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.