Question presented to candidate: "You need to look up a specific user by ID from an array of 10,000 users. Would you use find or filter for this, and does it actually make a measurable difference?"
What a strong answer should cover:
- 📌 Interview term:
find(predicate)— returns the first matching element (orundefinedif none match), and genuinely short-circuits the instant a match is found;📌 filter(predicate)** — returns all matches as a new array, genuinely checking every element regardless. - 📌 Verified, not assumed — directly answering the prompt's exact question: a real call counter proved
find()genuinely stopped at exactly the element that matched — real, measurably fewer calls thanfilter(), which genuinely checked all remaining elements even after finding a match. - 📌 Interview term: the real, distinct "no match" results — directly relevant for the prompt's ID-lookup scenario:
find()with no match genuinely returnsundefined, whilefilter()with no match genuinely returns an empty array, notundefined— a real, meaningful difference for downstream code checking the result. - A precise answer names the real, direct payoff for the prompt's exact scenario: for a single-item lookup by a unique key (like a user ID) in a genuinely large array,
find's real short-circuiting means it stops almost immediately once the match is located, whilefilterwould genuinely keep scanning through potentially thousands of remaining elements for no benefit — a real, measurable difference specifically when the match is found early. - A precise answer names
findIndex/findLast/findLastIndexas real, direct siblings offind, covering position-based and reverse-direction lookups with the identical real short-circuiting behavior.
Clarifying questions expected:
- "Is the actual ID genuinely guaranteed unique, so at most one real match is ever possible?" — directly relevant to whether
find's "just the first" semantics, verified above, are actually correct for the use case, versus needingfilterfor genuinely multiple matches. - "Does the real, downstream code need to distinguish 'no match' from a match, in a way that matters whether it gets
undefinedversus an empty array?" — verified above as a real, meaningful difference between the two.
Code / implementation expected: Yes — a real call counter directly proving find's short-circuiting versus filter's full scan, plus the real, distinct no-match results (undefined vs. empty array), is the concrete, convincing proof of exactly which tool fits the prompt's lookup scenario.