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
Syntax
const match = array.find((item) => test);
array: the array to search.(item) => test: a function thatfind()calls with each item in turn. Write a test that’struefor the item you want.match: the first item whose test wastrue, orundefinedif there wasn’t one.find()stops at the first match.
See Array.prototype.find() on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page.
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.js
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
Terminal
node find.js
Output
{ 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
| Mistake | What happens | Do 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 undefined | Compare 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
- Array.prototype.find() (MDN)
- Strict equality (===) (MDN)
- Run Node.js scripts from the command line (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
