Array find() and findIndex(): first match (ES2015)
What you’ll learn
Section titled “What you’ll learn”- What
find()andfindIndex()return, and how they differ fromfilter(),some()andindexOf(). - The edge cases: short-circuiting, holes, appended elements and the “found
undefined” ambiguity. - How to update an array element immutably with
findIndex(). - When a linear search is the wrong tool and a
Mapis better.
Summary
Section titled “Summary”TL;DR: array.find(predicate) returns the first element for which predicate returns a truthy value, or undefined. array.findIndex(predicate) returns that element’s index, or -1. Both stop at the first match.
Both were added in ECMAScript 2015 and work in every current browser and runtime. To search from the end, use findLast() and findLastIndex() (ES2023).
The problem it solves
Section titled “The problem it solves”Before ES2015, indexOf() could only compare values with ===. To find an object by a condition, such as “the first pending order” in the invented OrdersPortal app, you wrote a loop or used filter()[0], which tests every element and builds a new array only to read one item.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. The outputs shown were produced with Node.js 22.23.
const orders = [ { id: 'o-101', customer: 'c-7', status: 'paid', total: 120 }, { id: 'o-102', customer: 'c-3', status: 'pending', total: 45 }, { id: 'o-103', customer: 'c-7', status: 'pending', total: 80 },];
// Before ES2015: a loop, or filter()[0], which scans the whole array and allocates a new one.let firstPending;for (let i = 0; i < orders.length; i++) { if (orders[i].status === 'pending') { firstPending = orders[i]; break; }}console.log(firstPending.id); // o-102console.log(orders.filter((o) => o.status === 'pending')[0].id); // o-102
// After: find returns the first matching element, findIndex its index.console.log(orders.find((o) => o.status === 'pending').id); // o-102console.log(orders.findIndex((o) => o.status === 'pending')); // 1console.log(orders.find((o) => o.status === 'refunded')); // undefinedconsole.log(orders.findIndex((o) => o.status === 'refunded')); // -1How it works
Section titled “How it works”// Fragment: signaturesarray.find(predicate, thisArg?) // element or undefinedarray.findIndex(predicate, thisArg?) // index or -1// predicate(value, index, array) -> truthy to stop- The predicate receives the element, its index and the array. Its return value is coerced to a boolean, so any truthy value counts as a match.
- The search runs in ascending index order and stops at the first match.
thisArgsetsthisinside a regular-function predicate; arrow functions ignore it.- Both methods are generic: they work on any array-like object through
Array.prototype.find.call(...), and typed arrays have their own versions. - If the predicate is not callable, they throw a
TypeErrorbefore reading any element.
The specification implements find, findIndex, findLast and findLastIndex with one shared operation, FindViaPredicate, which explains the edge cases below:
// Short-circuit: the predicate stops at the first match.const visited = [];[5, 12, 8, 130].find((n, i) => { visited.push(i); return n > 10; });console.log(visited); // [ 0, 1 ]
// Holes are visited as undefined (forEach, filter and some skip them).const sparse = [1, , 3];console.log(sparse.findIndex((v) => v === undefined)); // 1let calls = 0;sparse.forEach(() => calls++);console.log(calls); // 2
// The element can itself be undefined: find cannot tell you whether it matched.const values = [undefined, 0];console.log(values.find((v) => v === undefined)); // undefined (found!)console.log(values.findIndex((v) => v === undefined)); // 0
// The range is fixed before the first call: appended elements are not visited.const queue = [1, 2];console.log(queue.find((n) => { if (n === 1) queue.push(99); return n === 99; })); // undefined
// It returns the element itself, not a copy.const list = [{ id: 'a', qty: 1 }];list.find((x) => x.id === 'a').qty = 5;console.log(list[0].qty); // 5
// It is generic: it works on any array-like object.const arrayLike = { length: 2, 0: 'x', 1: 'y' };console.log(Array.prototype.find.call(arrayLike, (v) => v === 'y')); // y
// The predicate must be callable.try { [1].find('id'); } catch (e) { console.log(e.constructor.name, '-', e.message); }// TypeError - string "id" is not a functionThe TypeError message is V8’s wording; other engines phrase it differently.
TypeScript
Section titled “TypeScript”find() has an overload that accepts a type predicate, and since TypeScript 5.5 an inline arrow such as (o) => o.status === 'paid' is inferred as one. The result type is narrowed, plus undefined:
// Fragment: type-checks with TypeScript 6.0.3 and 7.0.2 (--strict)type Order = | { id: string; status: 'pending' } | { id: string; status: 'paid'; paidAt: string };declare const orders: Order[];
const paid = orders.find((o) => o.status === 'paid'); // { id; status: 'paid'; paidAt } | undefinedconst paidAt: string | undefined = paid?.paidAt;Realistic example
Section titled “Realistic example”The OrdersPortal cart adds items without mutating the existing cart, and reports the first line that breaks a per-product quantity limit. findIndex() gives the position to replace; find() gives the element for the error message.
// cart.mjs - OrdersPortal cart updates without mutating the existing cart.function addToCart(cart, sku, qty = 1) { const index = cart.findIndex((line) => line.sku === sku); if (index === -1) { return [...cart, { sku, qty }]; } // with() (ES2023) returns a copy with one element replaced. return cart.with(index, { ...cart[index], qty: cart[index].qty + qty });}
function firstOverLimit(cart, limits) { // find gives you the element; you need it for the error message. return cart.find((line) => line.qty > (limits[line.sku] ?? Infinity));}
let cart = [];cart = addToCart(cart, 'SKU-MUG');cart = addToCart(cart, 'SKU-TEE', 2);cart = addToCart(cart, 'SKU-MUG', 3);console.log(cart);
const offending = firstOverLimit(cart, { 'SKU-MUG': 3 });if (offending) { console.log(`Limit exceeded for ${offending.sku}: ${offending.qty}`);}Output:
[ { sku: 'SKU-MUG', qty: 4 }, { sku: 'SKU-TEE', qty: 2 } ]Limit exceeded for SKU-MUG: 4Array.prototype.with() needs Node.js 20 or a browser from 2023 onward; on older runtimes, copy with slice() and assign by index.
Common mistakes
Section titled “Common mistakes”- Treating
findIndex()as a boolean. Index0is falsy and-1is truthy, soif (cart.findIndex(...))is wrong both ways. Compare with-1. - Using
find()to test existence. If the matching element can beundefined,0or'', a truthiness check on the result lies. Usesome()for a yes/no answer, orfindIndex(). - Assignment instead of comparison.
find((o) => o.status = 'paid')returns the first element and overwrites its status. Lint rules such asno-return-assigncatch it. - Expecting a copy.
find()returns a reference; mutating it mutates the array’s element. - Calling
find()inside a loop. Each call is a linear scan, so looking up 5,000 SKUs in 5,000 products is 25 million comparisons in the worst case. Build aMapkeyed by SKU once and callget(). - Mutating the array in the predicate. The visited range is fixed up front, so appended elements are skipped and deleted ones read as
undefined. Keep predicates pure.
When to use it and when not to
Section titled “When to use it and when not to”| You want | Use | Returns |
|---|---|---|
| The first element matching a condition | find() |
element or undefined |
| Its position (to replace, remove or slice) | findIndex() |
index or -1 |
| The last match | findLast() / findLastIndex() |
element / index |
| Every match | filter() |
new array |
| Only whether something matches | some() |
boolean |
| Whether a known value is present | includes() |
boolean |
| Repeated lookups by key | Map.prototype.get() (Map and Set) |
value or undefined |
For lazy sources such as generators or map.values(), ES2025’s iterator helpers add Iterator.prototype.find() (Node.js 22, Chrome 122, Firefox 131, Safari 18.4), which searches without first copying into an array.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, find() and findIndex() are supported in Chrome 45, Edge 12, Firefox 25, Safari 8, Node.js 4, Deno 1.0 and Bun 1.0. Internet Explorer never supported them. TypeScript’s types are in lib.es2015.core.d.ts, included by every modern target. For legacy runtimes, core-js provides polyfills.
Interview questions
Section titled “Interview questions”1. What is the difference between find() and filter()?
find() returns the first matching element (or undefined) and stops searching. filter() tests every element and always returns a new array, possibly empty. Use filter() only when you need all matches.
2. Why might find() returning undefined not mean “not found”?
Because the matching element can itself be undefined, including a hole in a sparse array, which find() visits as undefined. If that is possible, use findIndex() and compare with -1, or some().
3. Do find() and forEach() treat holes in sparse arrays the same way?
No. find(), findIndex() and includes() visit every index from 0 to length - 1 and read holes as undefined. forEach(), filter(), some() and indexOf() skip holes.
4. Senior scenario: an import job matches 50,000 incoming order lines against 20,000 products using products.find(), and it is slow. What do you change?
Each find() is O(n), so the job is O(lines × products). Build a Map from product key to product once (O(n)), then look up each line in O(1) on average. Keep find() for one-off searches on small arrays, and decide what happens on a missing key (skip, collect as an error or fail the import) explicitly rather than reading a property of undefined.
Key takeaways
Section titled “Key takeaways”find()returns the first matching element orundefined;findIndex()returns its index or-1. Both short-circuit.- They visit holes as
undefinedand fix the range before the first call. - Use
findIndex()orsome()when a matching element could beundefined, and compare indexes with-1. - For repeated lookups by key, a
Mapbeats repeated linear searches.
Related pages
Section titled “Related pages”- Array findLast() and findLastIndex(): the same search from the end (ES2023).
- Array includes(): presence of a known value, without a callback.
- Array at(): read an element by position, including from the end.
- Array with(): replace an element by index without mutating.
- Map and Set: keyed lookups for repeated searches.
- Arrow functions: the usual way to write predicates.
- JavaScript arrays
Official references
Section titled “Official references”- ECMAScript Language Specification:
Array.prototype.find,Array.prototype.findIndexandFindViaPredicate(current draft; first published in ECMAScript 2015) - ECMAScript 2015 Language Specification:
Array.prototype.find - MDN: Array.prototype.find()
- MDN: Array.prototype.findIndex()
- MDN: Iterator.prototype.find()