DEV Community

Cover image for JavaScript Array.some() or Array.every()?
Rakhi
Rakhi

Posted on

JavaScript Array.some() or Array.every()?

I recently started using array.some() and at the same time also found array.every() interesting. It saved time for me, might do the same to you!

We will talk about both methods here.

Array.some()

  1. It will return True if any element matches the required condition.
  2. You would want to use this method in case you want to check if at least one of the elements in the array matches the constraints.
  3. Array.some() will always return false if the array is empty. But then we ask why so? It is because array.some() returns true if at least one element of an array passes your condition. If the array is empty, none of the elements pass the condition and hence it returns false.
Let's check out Array.some() examples:
  • Check if there is a negative number in the array:

  • Check if value exists in the array:

  • What if there is an empty array and you also need to use array.some()? It is possible to do that but note it will always return False as mentioned before:

Array.every()

  1. It returns True if all the elements in the array match your condition.
  2. You would want to use this method in case you want to check if all the elements in the array match your condition.
  3. It returns True if the array is empty. Then we again ask, hey, why? It is because array.every() returns true if every element of an array passes the condition. If there are no items in the array, every element in the array passes the condition, hence it returns true.
Let's check out Array.every() examples:
  • Check if every number in array is negative:

  • For empty array it will always return True:

Top comments (5)

Collapse
 
aminnairi profile image
Amin

Very nice explanations, Rakhi, thanks!

You could even use some higher-order functions to create a slick little API for checks that we often use on arrays.

"use strict";

const is = searchedItem => item => item === searchedItem;
const hasLengthGreaterThan = length => item => item.length > length;

const fruits = ["banana", "pear", "apple", "strawberry"];

const hasStrawberry = fruits.some(is("strawberry")); // true
const hasLongName = fruits.some(hasLengthGreaterThan(15)); // false
Enter fullscreen mode Exit fullscreen mode
Collapse
 
arvindsridharan profile image
arvindsridharan

It would be great if you could cover higher order functions in detail.

Collapse
 
aminnairi profile image
Amin
Collapse
 
terabytetiger profile image
Tyler V. (he/him)

Great breakdown! I feel like I never remember these exist 😅

Collapse
 
atbrakhi profile image
Rakhi • Edited

Definitely!!

For the includes() and indexOf(), I agree! I have personally used both methods in my codebase, I might end up writing another post for them.

Thanks for sharing Luke.