DEV Community

Dina Andrandraina
Dina Andrandraina

Posted on

Javascript - Array.some() and Array.every()

Javascript provides interesting tools to work with Arrays and Objects. In this article, we will talk about two array methods: some and every.

Array.some()

If you want to check if your array has a value that matches a condition, Array.some() is your friend. It just takes a callback with 4 parameters:

  • the current element
  • the index of the item
  • the original array
  • and a value to use as this;

and returns a boolean. Note that only the first parameter is required for the callback, all the others are optionals.

As soon as the item makes the callback return a truthy value, Array.some returns true directly.

Let's take an example. Let's check if our array has an even number.

Here's our original arrays:

const arr1 = [1,3,17,9,5];
const arr2 = [1,17,8,7];
Enter fullscreen mode Exit fullscreen mode

Without using the Array.some() method, we'd probably did it like this:

function hasEven(arr) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] % 2 === 0) return true;
    }

    return false;
}

console.log(hasEven(arr1)) // false
console.log(hasEven(arr2)) // true
Enter fullscreen mode Exit fullscreen mode

This is quite long for just checking if our array matches a condition.

With Array.some, we can make this in a single line:

console.log(arr1.some(item => item % 2 === 0)) // false
console.log(arr2.some(item => item % 2 === 0)) // true
Enter fullscreen mode Exit fullscreen mode

But wait, we're repeating some logic here, that's not DRY.

Okay, you're right. Let's refactor it.

const isEven = n => n % 2 === 0;
console.log(arr1.some(isEven)); // false
console.log(arr2.some(isEven)); // true
Enter fullscreen mode Exit fullscreen mode

Alternatively:

console.log(arr1.some(n => isEven(n)))
Enter fullscreen mode Exit fullscreen mode

We did it, now we have a shorter code, readable and DRY.

Readable? Yes, you can read it like:

  • some element of arr1 is even => false
  • some element of arr2 is even => true

Array.every()

This array method is similar to Array.some, the difference is that it returns true only if each element of the given array makes the callback return a truthy value.

const arr1 = [2,8,6,1,4,16];
const arr2 = [16,20,14,4,2];
const isEven = n => n % 2 === 0;

console.log(arr1.every(isEven)); // false
console.log(arr2.every(isEven)); // true
Enter fullscreen mode Exit fullscreen mode

Conclusion

Array.some() checks if the given array contains some value that makes the given callback return a truthy value.

Array.every() checks if every element in the array matches the given callback.

Top comments (0)