JavaScript · The language round
When should you use some, every, find or includes?
Short answer
some asks whether any item matches, every asks whether all do, find returns the first matching item, and includes checks for a specific value. They short-circuit and do not mutate the array.
These methods answer different questions. Picking the right one makes intent obvious and avoids unnecessary work because most of them stop as soon as the answer is known.
const numbers = [1, 2, 3, 4];
numbers.some((n) => n > 3); // true
numbers.every((n) => n > 0); // true
numbers.find((n) => n % 2 === 0); // 2
numbers.findIndex((n) => n > 10); // -1
numbers.includes(3); // trueThe differences
somereturns a boolean as soon as one callback returns trueeveryreturns a boolean as soon as one callback returns falsefindreturns the first matching element, orundefinedfindIndexreturns the index of the first match, or-1includesuses SameValueZero, so it findsNaNand treats-0and0as equal
On an empty array, some returns false and every returns true. That follows the usual logical identities: no element satisfies the predicate, and no element violates it.
[].some(() => true); // false
[].every(() => false); // true
[NaN].includes(NaN); // true
[NaN].indexOf(NaN); // -1filter. If you need the index, use findIndex.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What does `every` return for an empty array?
- 2Why does `includes` find NaN but `indexOf` does not?
- 3What is the difference between `find` and `filter`?
- 4How do you check whether an array contains an object by property value?
Say it in the interview
some checks whether at least one item matches and returns a boolean. every checks whether all items match. find returns the first matching element, and findIndex returns its index. includes checks for a specific value using SameValueZero, so it finds NaN. They all short-circuit. On an empty array, some is false and every is true, which is the logical identity.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.