When should I use the .every() method vs the .some() method?

Question

When should I use the .every() method vs the .some() method?

Answer

We can use the .every() method when we want to check if a condition is true for each element in an array, if an element does not pass our test provided to the .every() method, .every() will return false - meaning that at least one element in the array did not pass our test.
For example:

var myArray = [4, 7, 2, 19, 9];

function isBelowTen(num) {
  return num < 10; //returns a boolean value - true if num is less than 10, false if num is equal to or greater than 10
}

myArray.every(isBelowTen); //returns false because one of the elements in the array did not pass our test

We can use the .some() method instead when we want to check if some of the elements in our array pass a given test, if an element passes the given test, .some() will return true - meaning that at least one element in the array passed our test.
For example:

var myArray = [4, 7, 10, 42, 9];

function isGreaterThanTen(num) {
  return num > 10; //returns a boolean value - true if num is greater than 10, false if num is equal to or less than 10
}

myArray.some(isGreaterThanTen); //returns true because at least one of the elements in the array passes our test

For the isTheDinnerVegan() code challenge, .every() is the most direct:
return arr.every(element => element.source === 'plant');

But you could also use .some() because its double negation is logically equivalent:
return false == arr.some(element => element.source != 'plant');
In other words, “every source is plant” is the same as “not any (some) source is not plant.”

4 Likes

Helloo
Why in the code solution of the exercise below, the “If” can’t be like this food.source === 'plant' ? true : false with ternary operator? it seems it doesn’t work and it is the same with the other If inside the for loop.

function isTheDinnerVegan(arr) {
      const isVegan = (food) => {
            if (food.source === 'plant') {
                  return true;
            }
            return false;
      }
      for(let i = 0; i<arr.length; i++){
            if (!isVegan(arr[i])){
                  return false 
            }
      }
      return true
}

can’t we use filter method for this;