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
On this page

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

    The this value inside the function.

More examples

#
Using the result safely
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 be undefined. Guard the property access with ?..
  • To check only whether an element exists, some() is better: it returns true or false.

Related entries

#

Spotted a mistake or missing an example? Write to us.