JavaScript

This page explains how find() returns the first array element that satisfies a condition.

Goal: retrieve the first match and handle undefined safely when no element matches.

find()

Use find() when you need one matching element. JavaScript checks the array from the beginning and stops as soon as the callback returns true.

A small example

JavaScript

const numbers = [3, 7, 12, 18];
const result = numbers.find(number => number > 10);

console.log(result); // 12

Although both 12 and 18 are greater than 10, the result is only 12 because it is the first match.

When nothing matches

If no callback call returns true, find() returns undefined. Check the result before using its properties or methods.

JavaScript

const user = users.find(user => user.id === requestedId);

if (user === undefined) {
  console.log("User not found");
} else {
  console.log(user.name);
}

find() or filter()?

Related topics