JavaScript Reference ยท Array
JavaScript Array find() method
Reference for JavaScript Array find(): return the first element that passes a test, or undefined, with callback arguments, edge cases and examples.
The find() method returns the first element in an array for which your callback returns a truthy value. If nothing matches, it returns undefined. It stops looking as soon as it finds a match.
Use it when you want the item itself, such as the user with a given id. If you need the position instead, use findIndex(); if you need all matches, use filter().
[5, 12, 8].find((n) => n > 10); // 12
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
find(callbackFn) find(callbackFn, thisArg)
| Name | Description |
|---|---|
callbackFn |
Called as callbackFn(element, index, array). Return a truthy value when the element is the one you want. |
thisArg |
Optional. Value used as this inside callbackFn (ignored by arrow functions). |
Return value: the first element that passed, or undefined if none did.
Exceptions: a TypeError if callbackFn is not a function.
Usage notes
- It stops at the first match. Later elements are never visited, so order matters when several elements would pass.
undefinedis ambiguous. A result ofundefinedcan mean "not found" or "found an element whose value isundefined". If the array may containundefined(or you cannot tell0or""from "missing"), usefindIndex()and compare with-1.- It returns the element, not a copy. For an object, you get a reference to the same object, so changing it changes the array's content (see the last example).
- Always guard the result before using it:
users.find(...)?.name ?? "unknown". - Holes are visited. Unlike
filter()orsome(),find()calls the callback for empty slots of a sparse array, passingundefined. - Searching for a plain value: use
includes()orindexOf();find()is for conditions. - Last match: use
findLast()to search from the end. - Many lookups: calling
find()in a loop is O(nยฒ). For repeated lookups by id, build aMaponce.
Browser support
find() is supported in every current browser.