Return the first element that matches a test.

Finding a Match

find_match.js
const wanted = 3;
const ids = [1, 3, 4, 7];
const found = ids.find((id) => id === wanted);
const label = found === undefined ? "none" : String(found);

console.log("wanted=" + wanted);
console.log("found=" + label);

Stop at the First Match

  1. Start with ids: [1, 3, 4, 7].
  2. find checks one id at a time.
  3. The first true result is returned.
  4. Later ids are not checked after a match is found. | Checked id | id === wanted | What happens | | --- | --- | --- | | 1 | false | keep looking | | 3 | true | return 3 | | 4 | not checked | already stopped |
find-match `find` stops when the callback first returns `true`. If nothing matches, it returns `undefined`.

Exercise: find_match.js

Use find to return the first matching id, then print none when no id matches