find and findIndex: Get the First Match

Grade 10, page 5 of 12. A one-minute read.

Sometimes you don't want all the matches. You just want the first one. That's find:

JavaScript
const users = [
  { id: 101, name: "Sofia" },
  { id: 102, name: "Kenji" },
  { id: 103, name: "Leah" },
];

const user = users.find((u) => u.id === 102);
console.log(user);

const nobody = users.find((u) => u.id === 999);
console.log(nobody);

It prints

{ id: 102, name: 'Kenji' }
undefined

find returns the item itself (not an array), or undefined if nothing matches. It stops searching as soon as it finds a match, so it's efficient.

findIndex works the same way, but gives you the item's index instead (or -1 if there's no match), which is handy when you want to change or remove the item:

JavaScript
const index = users.findIndex((u) => u.name === "Leah");
console.log(index);

users.splice(index, 1);
console.log(users.map((u) => u.name));

It prints

2
[ 'Sofia', 'Kenji' ]
Tipfilter vs find
  • filter returns an array of all matches (possibly empty).
  • find returns the first match itself (or undefined).

If you're looking up one specific thing (like a user by their ID), use find. If you want a list of everything that matches, use filter.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning