Finding with find
Learn to return the first matching element with find.
Finding with find
The find method returns the first element that passes the test. It gives back the element itself, not an array or an index. If nothing matches, you get undefined.
So find means 'grab one and ignore the rest'. It fits when you need the first user with an admin role in a list. Distinguish it from cases where later matches matter too.
The difference between find and filter
find returns a single element, while filter returns an array. The former stops at the first match; the latter collects them all.
When only one result is useful, find is cleaner. For instance, to grab the first free seat in a list, find is enough. If you want to list every free seat, you need filter.
Exercise Find the first adult user
From the users array, find the first user whose age is 18 or higher and store it as firstAdult. Print the result.
Show example solution
const users = [{name: "Ed", age: 16}, {name: "Ada", age: 22}, {name: "Bob", age: 30}];
// find the first adult
const firstAdult = users.find(u => u.age >= 18);
console.log(firstAdult);
Exercise Find the first grade above the threshold
From the grades array, find the first grade greater than 50 and store it as firstPass. Print the result.
Show example solution
const grades = [20, 45, 55, 80];
// find the first grade above 50
const firstPass = grades.find(grade => grade > 50);
console.log(firstPass);
Test yourself
-
What is r after const r = [1,2,3].find(n => n > 10);?
const r = [1, 2, 3].find(n => n > 10);- -1
- undefined
- null
- []
Show answer
undefined — Correct. No number is greater than 10, so find returns undefined.
-
find the first adult user
const users = [{age: 17}, {age: 21}, {age: 30}]; const adult = users.find(u => ____); console.log(adult);Show answer
const users = [{age: 17}, {age: 21}, {age: 30}]; const adult = users.find(u => u.age >= 18); console.log(adult);