JavaScriptArrays
Array. prototype. find()
Returns the first element that matches a condition, or undefined.
- Returns
- The first matching element, or
undefined. - Changes the original
- No
Example
#JavaScript
const users = [
{ id: 1, name: 'Emma' },
{ id: 2, name: 'Jack' },
{ id: 3, name: 'Mia' }
]
console.log(users.find((user) => user.id === 2))
console.log(users.find((user) => user.id === 9))Console
{ id: 2, name: 'Jack' }
undefined
Definition and usage
#The find() method searches the array from the start and returns the first element for which the testing function returns a truthy value. If none match, it returns undefined.
The search stops at the first match, so on large arrays it’s faster than filter(), which always checks every element.
If you need the element’s position instead of the element itself, use findIndex(). To search from the end, there’s findLast() and findLastIndex().
Syntax
#Syntax
array.find(callbackFn)
array.find(callbackFn, thisArg)Parameters
#callbackFn
function (element, index, array)
The testing function. The search stops as soon as it returns a truthy value.thisArg
optional
Thethisvalue inside the function.
More examples
#JavaScript
const courses = [{ slug: 'html', title: 'HTML and CSS' }]
const course = courses.find((c) => c.slug === 'python')
console.log(course?.title ?? 'Course not found')Console
Course not found
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- The result of
find()can beundefined. Guard the property access with?.. - To check only whether an element exists,
some()is better: it returnstrueorfalse.
Related entries
#- find() vs filter()find() returns the first element that matches a condition, or undefined, while filter() returns a new array with every element that passed the test.
- Array.prototype.findIndex()Returns the index of the first element that matches a condition, or -1.
- Array.prototype.findLast()Returns the last element that matches a condition, searching the array from the end.
- Array.prototype.filter()Creates a new array with the elements for which the function returned true.
- Array.prototype.some()Checks whether at least one element matches a condition.
Spotted a mistake or missing an example? Write to us.