JS: Array.prototype.find

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2015)

xArray.find(f)
  • Return the first element of array xArray where the function f returns true.
  • Return undefined if not found.
  • f is a function. The function should return true or false.

f is passed 3 args:

  1. currentElement
  2. currentIndex
  3. xArray
xArray.find(f , thisArg)
Use thisArg for this (binding) of f
// 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 is 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);

JavaScript. Array Search