Syntax
items.find((item, index, array) => condition)
items.findIndex((item, index, array) => condition)
items.findLast((item, index, array) => condition)
items.findLastIndex((item, index, array) => condition)Examples
Look up a lesson safely
The optional chain handles a missing object. A valid match may also be 0, false or an empty string, so a truthiness check is not a general test for success.
const lessons = [{ id: "arrays", title: "Working with arrays" }];
const lesson = lessons.find(item => item.id === "loops");
console.log(lesson?.title ?? "Lesson not found"); // Lesson not found
const score = [0, 5, 10].find(value => value < 3);
console.log(score); // 0
console.log(score !== undefined); // trueCheck the index before removing an item
If there is no match, leave the list alone. Passing -1 to splice() would remove the last saved topic.
const saved = ["arrays", "functions"];
const index = saved.findIndex(topic => topic === "loops");
if (index !== -1) {
saved.splice(index, 1);
}
console.log(index); // -1
console.log(saved); // ["arrays", "functions"]Find the latest passing attempt
Starting from the end makes the intended order explicit. The returned index still counts from the beginning.
const attempts = [{ score: 4 }, { score: 9 }, { score: 7 }];
console.log(attempts.findLast(attempt => attempt.score >= 8)); // { score: 9 }
console.log(attempts.findLastIndex(attempt => attempt.score >= 8)); // 1
console.log([undefined].findIndex(value => value === undefined)); // 0
console.log([].findIndex(value => value === undefined)); // -1Parameters and values
- predicate: Receives the item, its index and the original array. A truthy return value means a match. These methods also visit empty slots as undefined, so guard property access when an array may contain gaps.
- Return value: find/findLast return the matched value, or undefined. findIndex/findLastIndex return its index, or -1. Use an index method if undefined itself could be a valid match.
- thisArg (optional): A second argument can supply this for a regular predicate function. It does not change this inside an arrow function.
Best practices
- Use filter() when you need every matching item; find() deliberately stops at the first match.
- Keep the predicate synchronous. An async predicate returns a truthy Promise, not the eventual test result.
- Check the linked compatibility tables before using findLast or findLastIndex in older browsers or runtimes.
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification