Skip to main content
0 reactions

How to Find an Item in an Array with find() in JavaScript

Card titled find() in JavaScript, labelled JavaScript basics, with three ticked lines: book.id === 2 in quotes, which gives the matching book, and no match gives undefined.
How to Find an Item in an Array with find() in JavaScript

find() looks through an array and gives back the first item that passes a test you write. If no item passes, it gives back undefined.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
const match = array.find((item) => test);
  • array: the array to search.
  • (item) => test: a function that find() calls with each item in turn. Write a test that’s true for the item you want.
  • match: the first item whose test was true, or undefined if there wasn’t one. find() stops at the first match.

See Array.prototype.find() (opens in a new tab) on MDN.

Prerequisites

The Example

Two books, each an object with an id and a title. The code looks for the book with the ID '2', then for one with the ID '9', which doesn’t exist. It’s in a file named find.js.

Step 1: Write the Code

find.jsJavaScript
const books = [
  { id: '1', title: 'Salt and Starlight' },
  { id: '2', title: 'A Map of Quiet Places' },
];

console.log(books.find((book) => book.id === '2'));
console.log(books.find((book) => book.id === '9'));

Step 2: Run It

TerminalBash
node find.js
OutputPlain text
{ id: '2', title: 'A Map of Quiet Places' }
undefined

The first search gives back the whole matching book. The second finds nothing and gives undefined, so check for undefined before you use the result.

Common Mistakes

MistakeWhat happensDo this instead
Comparing a string with a number: book.id === 2 when the IDs are '2'=== also compares the type, so nothing matches and you get undefinedCompare values of the same type: book.id === '2'

FAQ

What if more than one item matches?

find() gives back only the first one. It stops searching there.

How do I get every match?

Use filter(), which gives back a new array of every item that passes the test.

Conclusion

array.find((item) => test) gives you the first matching item, or undefined when there’s none. Check for undefined before you use what it gives back.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments