JavaScript: Array.prototype.find

By Xah Lee. Date: . Last updated: .

New in ES2015.

Returns the first element of array myArray where the function f returns true. Returns undefined if not found.

If thisArg is given, it will be used as this value of f. If it is not given, undefined is used.

〔►see JavaScript: “this” Binding

f must be a function. The function should return true or false.

The function f is passed 3 args: • current_elementcurrent_indexmyArray.

// example of using array.find()

const isEven = (x => ( x % 2 === 0 ? true : false ) )

console.log( [7,3,4,2].find (isEven) ); // 4

// if not found, return undefined
console.log( [1,3,5].find (isEven) ); // undefined

Here's example using 2nd argument of predicate.

// get the first even value whose index is also even

const bothEven = ((x,i) => ( x % 2 === 0 && i % 2 === 0? true : false ) );

console.log( [7,2,4,3].find (bothEven) ); // 4

Note: Array.prototype.findIndex is the same, except that it returns the index.

〔►see JavaScript: Array.prototype.findIndex

Reference

ECMAScript® 2016 Language Specification#sec-array.prototype.find

Array Search Topic

  1. JavaScript: Array.prototype.indexOf
  2. JavaScript: Array.prototype.lastIndexOf
  3. JavaScript: Array.prototype.find
  4. JavaScript: Array.prototype.findIndex
  5. JavaScript: Array.prototype.includes

Array Topic

  1. JavaScript: Array Basics
  2. JavaScript: Understand JS Array
  3. JavaScript: Create Array
  4. JavaScript: Sparse Array
  5. JavaScript: Array-Like Object
  6. JavaScript: Array How-To

  1. JavaScript: Array Object
  2. JavaScript: Array.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.