Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.find

Returns the first element that passes a test.

Available since: ES2015

Syntax

array.find(callbackFn)

Parameters

ParameterTypeDescription
callbackFnFunctionA 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:

Oleg

When nothing is found, undefined is returned:

console.log([1, 2, 3].find((n) => n > 10));

Output:

undefined

Notes

The companion findIndex() returns the index rather than the element, or -1.

See also

Related recipes

In the tutorial

  • Searching arrays — How to find an element in a JavaScript array: includes, indexOf, find, findIndex, some and every.

Thanks for reading!

Donate to the site — we work hard for you.