liveBook · Manning

Find

As explained in Secrets of the JavaScript Ninja, Third Edition

A JavaScript method that returns the first array element satisfying a predicate, or undefined if none does.

Need one matching item from an array, rather than every match? `find` takes a callback that tests each item and returns the first item for which the callback returns true. If nothing matches, it returns `undefined`. section 10.1.4

Listing 10.8 Finding and filtering array items
const ninjas = [
  { name: "Yagyu", weapon: "shuriken" },
  { name: "Yoshi" },
  { name: "Kuma", weapon: "wakizashi" },
];
 
const ninjaWithWakizashi = ninjas.find((ninja) => {  #A
  return ninja.weapon === "wakizashi";  #A
});  #A
console.assert(
  ninjaWithWakizashi?.name === "Kuma" &&  #B
    ninjaWithWakizashi.weapon === "wakizashi",
  "Kuma is wielding a wakizashi",
);

const ninjaWithKatana = ninjas.find((ninja) => {
  return ninja.weapon === "katana";
});
console.assert(
  ninjaWithKatana === undefined,
  "We couldn't find a ninja that wields a katana",
);

const armedNinjas = ninjas.filter(  #C
  (ninja) => "weapon" in ninja,  #C
);  #C
console.assert(
  armedNinjas[0].name === "Yagyu" &&
    armedNinjas[1].name === "Kuma",
  "Yagyu and Kuma are armed",
);

The lookup for a wakizashi returns the matching ninja; the lookup for a katana returns `undefined`. The same listing uses `filter` when the goal is to collect all matching items. section 10.1.4

Account for a missing result before reading its properties; the example uses optional chaining when checking the found item's name. Choose `filter` instead when you need an array of every match, or `some` when you only need to know whether a match exists. section 10.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Demonstrates first-match lookup and an undefined result when no item matches, without implementing the method.
Examples
Tests weapon properties on an array of ninja objects, including a successful lookup and a missing match.
What you can do after
Apply it via JavaScript's Array.find to retrieve a first match and handle an undefined result.
How it connects
Contrasts find with filter for collecting matches and some for testing whether a match exists.

Also explained in

Compare how 5 books explain find →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.