Searching JavaScript Arrays: find, findIndex, findLast, includes, indexOf, some and every
Every way to search an array: includes and indexOf for exact values (and why indexOf can't find NaN), find, findIndex, findLast and findLastIndex for conditions, some and every for yes/no questions, the find-returns-0 trap, object identity, finding all matches, and when a Set or Map is faster.
kvi5hnuCode Sprout team member5 min readOn this page
"Is it there?", "where is it?", "give me the first one that matches", "do they all pass?" JavaScript arrays answer each of these with a dedicated method. Picking the right one makes code shorter and its intent obvious.

There are two families:
- Value search (
includes,indexOf,lastIndexOf) looks for an exact value. - Predicate search (
find,findIndex,findLast,findLastIndex,some,every) calls a test function on each element and stops as soon as the answer is known.
includes: is this value in the array?
arr.includes(value) (ES2016) returns true or false:
const allowedRoles = ["viewer", "editor", "admin"];
console.log(allowedRoles.includes("editor"), allowedRoles.includes("owner"));
console.log([1, NaN].includes(NaN), [1].includes("1"));
true false
true false
It compares with SameValueZero: strict equality, except that NaN matches NaN (article 23). No type conversion happens: 1 doesn't match "1".
indexOf and lastIndexOf: where is this value?
indexOf(value) returns the index of the first match, or -1 if there's none. lastIndexOf searches from the end. An optional second argument sets where to start, and negative values count from the end:
const visits = ["home", "cart", "home", "pay"];
console.log(visits.indexOf("home"), visits.lastIndexOf("home"), visits.indexOf("help"));
console.log(visits.indexOf("home", 1)); // start searching at index 1
0 2 -1
2
indexOf uses strict equality ===, which means it can't find NaN:
const readings = [3, NaN, 5];
console.log(readings.indexOf(NaN), readings.includes(NaN));
console.log(readings.findIndex(Number.isNaN));
-1 true
1
Use includes for "is it there?" and indexOf only when you need the position. Older code wrote arr.indexOf(x) !== -1 (or even ~arr.indexOf(x), a bitwise trick that's truthy unless the result is -1); includes replaced both.
Finding all occurrences
The start argument lets you continue a search after the previous match:
function indexesOf(arr, value) {
const found = [];
let i = arr.indexOf(value);
while (i !== -1) {
found.push(i);
i = arr.indexOf(value, i + 1);
}
return found;
}
console.log(indexesOf(["a", "b", "a", "a"], "a"));
[ 0, 2, 3 ]
Objects are found by identity
Value search compares references for objects (article 21). A different object with the same contents is a different value:
const saved = { id: 1 };
const list = [{ id: 1 }, saved];
console.log(list.indexOf({ id: 1 }), list.indexOf(saved), list.includes(saved));
console.log(list.findIndex((item) => item.id === 1));
-1 1 true
0
To search by content, use a predicate method.
find and findIndex: the first element that passes a test
find(fn) returns the first element for which fn returns a truthy value, or undefined. findIndex(fn) returns its index, or -1:
const users = [
{ id: 7, name: "Ana", admin: false },
{ id: 9, name: "Bo", admin: true },
{ id: 12, name: "Cy", admin: true },
];
console.log(users.find((u) => u.admin).name, users.findIndex((u) => u.admin));
console.log(users.find((u) => u.id === 99), users.findIndex((u) => u.id === 99));
Bo 1
undefined -1
Both stop at the first match, so the callback doesn't run for later elements. find returns the element itself, not a copy: changing the result changes the object inside the array.
findLast and findLastIndex
findLast and findLastIndex (ES2023) search from the end, which is handy for "the most recent" entry in a chronological list:
const users = [
{ id: 7, name: "Ana", admin: false },
{ id: 9, name: "Bo", admin: true },
{ id: 12, name: "Cy", admin: true },
];
console.log(users.findLast((u) => u.admin).name, users.findLastIndex((u) => u.admin));
Cy 2
Before ES2023, this took [...arr].reverse().find(...), which copies the array.
The falsy result trap
find returns the element, and the element itself might be falsy:
const stock = [3, 0, 5];
const empty = stock.find((n) => n === 0);
console.log(empty, empty ? "found" : "looks missing!");
console.log(stock.findIndex((n) => n === 0) !== -1, stock.includes(0));
0 looks missing!
true true
When the elements could be 0, "", false or null, check the result with !== undefined, or use findIndex, some or includes to test for presence.
some and every: yes/no questions
some(fn) returns true if at least one element passes the test. every(fn) returns true if all of them pass:
const ages = [16, 21, 34];
console.log(ages.some((a) => a < 18), ages.every((a) => a >= 18));
const isSorted = (arr) => arr.every((n, i) => i === 0 || arr[i - 1] <= n);
console.log(isSorted([1, 3, 4]), isSorted([3, 1, 4]));
true false
true false
Both short-circuit: some stops at the first true, every at the first false:
const checked = [];
[4, 7, 9].every((n) => {
checked.push(n);
return n % 2 === 0;
});
console.log(checked);
[ 4, 7 ]
On an empty array, some returns false and every returns true ("all zero elements pass", which is how logic defines it). That second one surprises people: [].every(isValid) is true, so check arr.length > 0 too when an empty list shouldn't count as valid.
console.log([].some(() => true), [].every(() => false));
false true
How search methods treat holes
find, findIndex, findLast, findLastIndex and includes visit holes as undefined; indexOf, lastIndexOf, some and every skip them (article 55). With normal, dense arrays this never matters.
When to use a Set or Map instead
Every array search checks elements one by one, so its cost grows with the array's length: O(n). That's fine for small arrays or occasional searches. When you search the same large collection repeatedly, build a lookup structure once:
const users = [
{ id: 7, name: "Ana" },
{ id: 9, name: "Bo" },
{ id: 12, name: "Cy" },
];
const ids = new Set(users.map((u) => u.id)); // membership
const byId = new Map(users.map((u) => [u.id, u])); // lookup by key
console.log(ids.has(9), byId.get(12).name);
true Cy
Set.has and Map.get take roughly constant time no matter how big the collection is. For example, checking 10,000 incoming IDs against 10,000 known IDs with includes does up to 100 million comparisons; with a Set, about 10,000 lookups. For sorted arrays, binary search is another O(log n) option (a classic interview exercise).
Common questions
includes or indexOf?
Use includes when you need a yes/no answer: it reads better and handles NaN. Use indexOf when you need the position.
find or filter?
find returns the first match (or undefined) and stops searching; filter returns an array of all matches and always checks every element. Use find when you expect one result, such as looking up by ID.
How do I search case-insensitively?
Use a predicate: the code below. For user-facing text in many languages, localeCompare with { sensitivity: "base" } also ignores accents (part 11).
words.some((w) => w.toLowerCase() === query.toLowerCase())
Why does [1, 2, 3].includes("2") return false?
includes doesn't convert types: the string "2" isn't the number 2. Convert first, for example arr.includes(Number(input)).
Summary
includes(value)answers "is it there?" with SameValueZero (findsNaN);indexOf/lastIndexOfreturn a position or -1 using===(can't findNaN).- Value search compares objects by reference; use a predicate to search by content.
find/findLastreturn the first/last matching element orundefined;findIndex/findLastIndexreturn its index or -1. All of them stop early.- A found element can be falsy, so test
!== undefined, or usefindIndex/some. someis "any",everyis "all"; both short-circuit, and on an empty arraysomeisfalseandeveryistrue.- For repeated lookups in large collections, use a
SetorMap.
Practice Questions
What does this print?
const a = [5, 12, 8, 130, 44];
console.log(a.find((n) => n > 10), a.findIndex((n) => n > 100), a.findLast((n) => n < 10));
Answer
12 3 8. The first element over 10 is 12, the first over 100 (130) is at index 3, and searching from the end, the first under 10 is 8.
What does [NaN, 0, -0].indexOf(NaN) return, and what about [NaN, 0, -0].includes(NaN) and [-0].includes(0)?
Answer
-1, true and true. indexOf uses ===, under which NaN never equals itself; includes uses SameValueZero, which treats NaN as equal to NaN and 0 as equal to -0.
Write hasDuplicates(arr) using an array method, then explain a faster approach.
Answer
const hasDuplicates = (arr) => arr.some((v, i) => arr.indexOf(v) !== i);
Is O(n²). Faster: new Set(arr).size !== arr.length, which is O(n).
A form is valid when every field passes isFilled. Why might fields.every(isFilled) approve a form that has no fields at all, and how do you guard against it?
Answer
every returns true for an empty array. Write fields.length > 0 && fields.every(isFilled).
Previous: JavaScript Array Iteration: forEach, map and filter Explained
Next: JavaScript reduce and reduceRight: Summing, Grouping, Counting and Building Objects

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.