.every() Method

The .every() array method is similar to .some(), but instead of checking that at least one item meets the callback criteria, it checks that callback criteria against every item in an array.

Consider the example given on the .some() post where we were checking the age of a group of people to see if any of them were of drinking age. Now let's check to see if everyone in that group is at least 21.

const ages = [14, 15, 16, 17, 22, 23, 24];

const olds = ages.every(age => age >= 21);
console.log(olds);
// expected output: false

Let's increase the complexity a little bit. Say you run a convenience store, and for regulatory reasons you need to make sure everything in your inventory is beer. Not wine, not liquor, not sake. Just beer. Also, you love beer, and like to drink it when you're doing inventory data input. You drink so much beer during this task that it makes you a little sloppy. Sometimes 'beer' is capitalized, sometimes it's not. Whatever. You decide to write a script to check your inventory to make sure all you have is beer.

const inventory = [
  {
    company: "Austin Beerworks",
    product: "Pearl Snap",
    type: "Beer",
  },
  {
    company: "TRVE Brewery",
    product: "Bring On the Clouds",
    type: "Beer",
  },
  {
    company: "Lone Star",
    product: "Lone Star Lite",
    type: "beer",
  },
  {
    company: "Independence",
    product: "Power & Light",
    type: "Beer",
  },
];

const allBeers = inventory.every(item => item.type.toLowerCase() === "beer");
console.log(allBeers);
// expected output: true

Sweet. Except now somehow some delicious red wine also made its way into your inventory:

const inventory = [
  {
    company: "Austin Beerworks",
    product: "Pearl Snap",
    type: "Beer",
  },
  {
    company: "TRVE Brewery",
    product: "Bring On the Clouds",
    type: "Beer",
  },
  {
    company: "Lone Star",
    product: "Lone Star Lite",
    type: "beer",
  },
  {
    company: "Independence",
    product: "Power & Light",
    type: "Beer",
  },
  {
    company: "Poggio Anima",
    product: "Lilith",
    type: "Red Wine",
  }
];

const allBeers = inventory.every(item => item.type.toLowerCase() === "beer");
console.log(allBeers);
// expected output: false

Well crap, there goes your weird beer-only liquor license.

Of note, .every() will run the callback function against every item in the array until it finds an item that doesn't meet the passed condition. At that point it will immediately escape and return false. Its behavior aims at checking each array item, but will return false at the first item that doesn't meet the criterion. As such it's kind of the inverse of .some(), which returns true and escapes at the first item that does meet the criteria.

From MDN: The .every() method checks if all elements in an array pass a test (provided as a function).

See more examples and documentation here.