find, includes, some & every in JavaScript
Four targeted searches cover nearly every question: find returns the first matching element (undefined when absent), findIndex its position (-1 when absent), includes tests membership with SameValueZero (finding NaN where indexOf fails!), and some/every collapse to booleans (any? all?).
All take optional thisArg/position tuning, all short-circuit where possible (some/every/find stop early), and indexOf/lastIndexOf remain for strict-equality position hunts. Choosing by question (which? where? any? all? contains?) replaces manual scan loops.
find/findIndex locate
First match or undefined/-1 β always check the miss value before using the result.
includes tests membership
[1, NaN].includes(NaN) is true (SameValueZero); indexOf would say -1 β includes wins for presence.
some/every decide
Any match? All match? β boolean answers with early exit, perfect for validation.
indexOf for positions
Strict-equality index hunts (plus lastIndexOf from the end) where the position itself matters.
let users = [{ name: "Ada", admin: true }, { name: "Bob", admin: false }];console.log(users.find(u => u.admin).name);console.log(users.some(u => u.admin), users.every(u => u.admin));Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself β building beats watching.