What's the Difference Between every() and some() in JavaScript?

JavaScript every() vs. some()

Introduced in ES5, the only difference between Array.prototype.some() and Array.prototype.every() is the following:

  • some() is used to check if at least one of the elements of the array passes the test implemented by the provided function;
  • every() is used to check if all the elements of the array pass the test implemented by the provided function.

To demonstrate the difference between the two, let's look at the following examples:

Using some()

The following example checks whether at least one element in the array is even or not:

// ES5+
function isEven(arr) {
    return arr.some(function (elem) {
        return elem % 2 === 0;
    });
}
const arr1 = [ 1, 3, 5, 2 ];
const arr2 = [ 1, 3, 5, 7 ];

console.log(isEven(arr1)); // output: true
console.log(isEven(arr2)); // output: false

If you're using ES6, you can use the arrow function with some() to make the syntax shorter, for example:

// ES6+
arr.some((elem) => elem % 2 === 0);

Using every()

The following example checks whether all elements in the array are even or not:

// ES5+
function allEven(arr) {
    return arr.every(function (elem) {
        return elem % 2 === 0;
    });
}
const arr1 = [ 2, 4, 6, 8 ];
const arr2 = [ 1, 2, 4, 6 ];

console.log(allEven(arr1)); // output: true
console.log(allEven(arr2)); // output: false

If you're using ES6, you can use the arrow function with every() to make the syntax shorter, for example:

// ES6+
arr.every((elem) => elem % 2 === 0);

Hope you found this post useful. It was published . Please show your love and support by sharing this post.