Array.prototype.find
Returns the first element that passes a test.
Available since: ES2015
Syntax
array.find(callbackFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| callbackFn | Function | A test function: the search stops at the first element for which it returns `true`. |
Return value
anyThe matching element, or `undefined` if nothing matched.
Examples
Finding an object by id:
const users = [
{ id: 1, name: 'Anna' },
{ id: 2, name: 'Oleg' },
];
console.log(users.find((user) => user.id === 2).name);Output:
OlegWhen nothing is found, undefined is returned:
console.log([1, 2, 3].find((n) => n > 10));Output:
undefinedNotes
The companion findIndex() returns the index rather than the element, or -1.
See also
- Array.prototype.filter — Creates a new array from the elements that pass a test.
- Array.prototype.some — Checks whether at least one element passes a test.
- Array.prototype.findIndex — Returns the index of the first element that passes a test.
- Array.prototype.findLast — Searches from the end of an array for the first element that passes a test.
Related recipes
In the tutorial
- Searching arrays — How to find an element in a JavaScript array: includes, indexOf, find, findIndex, some and every.