JavaScript: Array.prototype.find

By Xah Lee. Date: . Last updated: .

New in JS2015.

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

The function f is passed 3 args:

  1. current_element
  2. current_index
  3. arrayX.
arrayX.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

JS Array Search

BUY
ΣJS
JavaScript in Depth

JS Obj Reference

Array

prototype