CodeBlanks Logo Icon CodeBlanks

find and some

Learn search and check with .find and .some.

find and some

The find method returns the first element that matches a condition. If nothing matches, it returns undefined. Use find when you want only the first match, not all of them.

The some method asks whether at least one element matches. It does not return an array; it returns true or false. Use some when you care about existence, not the element itself.

Example: [1, 2, 3].find(n => n > 1) returns 2. [1, 2, 3].some(n => n > 2) returns true because 3 matches.

some versus every

The sibling of some is every. While some returns true when at least one element matches, every returns true only when all of them do. Both return a boolean, not an array.

On an empty array, some always returns false and every always returns true. This is a logical rule: with no items, the 'at least one' claim is false, while the 'all' claim is vacuously true.

Example: [2, 4, 6].every(n => n % 2 === 0) returns true because all are even. [1, 2, 3].every(n => n % 2 === 0) returns false.

Practice Find a user

Define an array of users [{name:"Ayşe",age:30}, {name:"Alex",age:17}, {name:"Mara",age:25}]. Use find to get the first user whose age is at least 18, and print that user's name with console.log.

Starter code

index.js
const users = [{name:'Ayşe',age:30}, {name:'Alex',age:17}, {name:'Mara',age:25}];
// Find the first user aged 18+ and print the name

Sample solution

index.js
const users = [{name:'Ayşe',age:30}, {name:'Alex',age:17}, {name:'Mara',age:25}];
const adult = users.find(u => u.age >= 18);
console.log(adult.name);

Expected output

Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does find return?

  • true
  • The first matching element Correct answer
  • All matches
  • A new array

Explanation: find returns the first element that matches.

2 Is anyone an adult?

Question
const ages = [12, 17, 21];
const hasAdult = ages.some(age => age ____ 18);
Answer
const ages = [12, 17, 21];
const hasAdult = ages.some(age => age >= 18);

Explanation: age >= 18 catches 21, so some returns true.

3 Match the methods

Term Meaning
find First matching element
some Is there at least one match
every Do all items match
undefined find's result when nothing matches

All lessons in Beginner