JavaScript Array.find() and findIndex() - Locate Elements
Learn Array.find() and findIndex() for locating elements by condition. Covers find vs filter, findLast (ES2023), and practical lookup patterns. Free reference.
Detailed Explanation
Understanding find() and findIndex()
Array.find() returns the first element that satisfies a testing function. Array.findIndex() returns the index of that element. Both short-circuit — they stop iterating as soon as a match is found.
Syntax
const element = array.find((el, index, array) => condition);
const idx = array.findIndex((el, index, array) => condition);
Basic Examples
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Carol" }
];
const bob = users.find(u => u.id === 2);
// bob: { id: 2, name: "Bob" }
const bobIndex = users.findIndex(u => u.id === 2);
// bobIndex: 1
const missing = users.find(u => u.id === 99);
// missing: undefined
find() vs filter()
| Method | Returns | Stops early? | Use when |
|---|---|---|---|
find() |
Single element or undefined | Yes | You need one result |
filter() |
Array of all matches | No | You need all results |
find() is more efficient when you only need the first match because it stops iterating immediately.
ES2023: findLast() and findLastIndex()
These search from the end of the array:
const nums = [1, 3, 5, 2, 4, 6];
nums.findLast(n => n > 3); // 6
nums.findLastIndex(n => n > 3); // 5
Useful for finding the most recent item in time-ordered data.
Practical Pattern: Update by ID
const items = [{ id: 1, qty: 5 }, { id: 2, qty: 3 }];
const idx = items.findIndex(i => i.id === 2);
if (idx !== -1) {
items[idx] = { ...items[idx], qty: items[idx].qty + 1 };
}
Use Case
Use find() for looking up records by ID, checking if an element exists while also retrieving it, and implementing search features. Use findIndex() when you need the position for splice or direct replacement operations.