JavaScript find Method
Table of Contents + β
In the previous lesson, we learned how to pull every matching item out of an array with filter. Now letβs learn how to grab just the first match with find.
π What is the find Method?
The find method goes through an array and returns the first element that passes a test you give it. You write the test as a function that returns true or false. As soon as one element returns true, find stops and hands that element back.
Unlike filter, which always returns an array, find returns a single item. If no element passes the test, find returns undefined.
Here is the basic shape:
const numbers = [4, 9, 12, 7, 20];
const firstBig = numbers.find((number) => number > 10);
console.log(firstBig); // 12Letβs walk through what each line does:
const numbers = [4, 9, 12, 7, 20]gives us the array to search.numbers.find((number) => number > 10)runs the testnumber > 10on each element in order.4and9fail the test, but12passes, sofindreturns12right away and ignores the rest.console.log(firstBig)prints that returned value,12.
π find vs filter
These two methods look similar but answer different questions. filter asks βwhich items match?β and gives you all of them in an array. find asks βwhat is the first item that matches?β and gives you that one item.
| Method | Returns | If nothing matches |
filter | An array of all matches | An empty array [] |
find | The first matching item | undefined |
Here they are side by side on the same array:
const numbers = [4, 9, 12, 7, 20];
console.log(numbers.filter((number) => number > 10)); // [12, 20]console.log(numbers.find((number) => number > 10)); // 12Both lines use the same test, number > 10, but return different shapes:
filtercollects every number that passes and returns them in an array,[12, 20].findstops at the first number that passes and returns it on its own,12.
π€ Finding an Object by id
The most common real use of find is locating one object inside an array of objects. You search by a unique value such as an id.
const users = [ { id: 1, name: "Alex" }, { id: 2, name: "Sam" }, { id: 3, name: "Jordan" },];
const user = users.find((user) => user.id === 2);
console.log(user); // { id: 2, name: "Sam" }console.log(user.name); // SamHere is how this finds the right object:
users.find((user) => user.id === 2)checksuser.id === 2on each object in order.- The first two objects fail until it reaches the one whose
idis2, which it returns. - We store that object in
user, soconsole.log(user)prints the whole object anduser.namereads just itsname,Sam.
find returns the item, not a copy
The object you get back is the same object that lives in the array. Changing a property on it will change it inside the array too.
π The findIndex Method
Sometimes you want the position of an item rather than the item itself. The findIndex method works just like find, but it returns the index of the first match. If nothing matches, it returns -1.
const users = [ { id: 1, name: "Alex" }, { id: 2, name: "Sam" }, { id: 3, name: "Jordan" },];
console.log(users.findIndex((user) => user.id === 2)); // 1console.log(users.findIndex((user) => user.id === 99)); // -1Each line searches for an id and reports a position instead of an object:
- The first line finds the user with
idof2, which sits at index1(the second slot), so it returns1. - The second line searches for
idof99, which no user has, sofindIndexreturns-1.
An index is useful when you need to update or remove the item at that spot in the array.
β οΈ Common Mistakes to Avoid
| Mistake | Problem | Solution |
Expecting an array from find | find returns one item, so array methods like .length fail | Use filter when you want an array of matches |
Not handling undefined | Reading a property of a missing result throws an error | Check the result exists before using it |
Confusing find with filter | You get the wrong shape of data back | find for one item, filter for many |
This is what the undefined problem looks like, and how to guard against it:
const users = [ { id: 1, name: "Alex" }, { id: 2, name: "Sam" },];
// β Throws if no user is foundconst user = users.find((user) => user.id === 99);console.log(user.name); // TypeError: Cannot read properties of undefined
// β
Check first, then use the result safelyif (user) { console.log(user.name);} else { console.log("No user found");}Here is what goes wrong and how the fix avoids it:
users.find((user) => user.id === 99)matches nothing, souserisundefined.- Reading
user.nameon thatundefinedvalue throws aTypeError, becauseundefinedhas no properties. - The
if (user)check runs theuser.nameline only when a real object was found, and falls back to"No user found"otherwise.
π§ Try It Yourself!
- Create an array of numbers and use
findto get the first one greater than100. - Build an array of objects with
idandname, then find the object with a specificid. - Use
findto search for anidthat does not exist and log the result. Notice it isundefined. - Use
findIndexto get the position of an item, then try anidthat is missing and confirm you get-1.
π§© What Youβve Learned
- β
findreturns the first element that passes the test, not an array - β
findreturnsundefinedwhen no element matches - β
filterreturns all matches as an array, whilefindreturns a single item - β
findIndexreturns the index of the first match, or-1if nothing matches - β
Always check for
undefinedbefore reading a property of the result
π Whatβs Next?
Now that you can pull a single item out of an array, we will learn how to boil an array down to one value. Letβs continue to reduce.