Lookup by identifier
Retrieve one record from an in-memory collection by an identifying property.
JavaScript · Function
find() returns the first array element for which a testing callback returns a truthy value. If no element matches, it returns undefined.
Call find() with a callback that evaluates each array element. Iteration proceeds from the lowest index; the first truthy callback result immediately produces that element, while a completely unsuccessful search produces undefined.
find(callbackFn)
find(callbackFn, thisArg)| Name | Type | Description |
|---|---|---|
callbackFn | Function | A function called for each array element. It should return a truthy value for a match and a falsy value otherwise; it receives the element, index, and array. |
thisArg | any | Optional value used as this when callbackFn executes. |
The first element satisfying the testing function; otherwise undefined.
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Linus" },
];
const user = users.find(({ id }) => id === 2);
console.log(user?.name); // "Linus"
console.log(users.find(({ id }) => id === 3)); // undefinedThe callback tests each user in order, and find() returns the first object whose id matches. Optional chaining safely handles the undefined result when no user matches.
Retrieve one record from an in-memory collection by an identifying property.
Select the first item meeting a threshold, status, or validation rule.
Search array-like data structures using length and integer-keyed properties.
find() calls the predicate in ascending index order and stops as soon as the predicate returns a truthy value. It returns that element; if no predicate call succeeds, it returns undefined.
Follow-up: How does it treat sparse arrays? It invokes the callback for every index, treating empty slots like undefined.
callbackFn receives the current element, its index, and the array being searched. An optional thisArg supplies the callback's this value when the callback is invoked.
Follow-up: What must the callback return? Any truthy value signals a match; a falsy value continues the search.
find() is generic: it only requires the this value to have a length property and integer-keyed properties. Therefore, it can operate on suitable array-like objects rather than only Array instances.
Follow-up: What happens when the callback never returns truthy? The complete traversal finishes and the method returns undefined.
Array.prototype.findIndex()Array.prototype.findLast()Array.prototype.filter()Array.prototype.some()