JavaScript Array find()

The JavaScript Array find() method returns the value of the first array element that satisfies the provided test function.

The syntax of the find() method is:

arr.find(callback(element, index, arr),thisArg)

Here, arr is an array.


find() Parameters

The find() method takes in:

  • callback - Function to execute on each element of the array. It takes in:
    • element - The current element of array.
  • thisArg (optional) - Object to use as this inside callback.

Return value from find()

  • Returns the value of the first element in the array that satisfies the given function.
  • Returns undefined if none of the elements satisfy the function.

Example 1: Using find() method

function isEven(element) {
  return element % 2 == 0;
}

let randomArray = [1, 45, 8, 98, 7];

firstEven = randomArray.find(isEven);
console.log(firstEven); // 8

// using arrow operator
firstOdd = randomArray.find((element) => element % 2 == 1);
console.log(firstOdd); // 1

Output

8
1

Example 2: find() with Object elements

const team = [
  { name: "Bill", age: 10 },
  { name: "Linus", age: 15 },
  { name: "Alan", age: 20 },
  { name: "Steve", age: 34 },
];

function isAdult(member) {
  return member.age >= 18;
}

console.log(team.find(isAdult)); // { name: 'Alan', age: 20 }

// using arrow function and deconstructing
adultMember = team.find(({ age }) => age >= 18);

console.log(adultMember); // { name: 'Alan', age: 20 }

Output

{ name: 'Alan', age: 20 }
{ name: 'Alan', age: 20 }

Recommended Reading: JavaScript Array.findIndex()