When working with arrays, it’s common to check whether elements meet certain conditions. You may already be familiar with Array.prototype.some(), which checks if at least one item passes a test. But what if you want to make sure every item passes?

Let’s look at the classic approach and then see how JavaScript’s every() method makes it simpler and more readable.

Classic Looping Method

var heroes = [
  { name: "Superman",     universe: "DC"     },
  { name: "Batman",       universe: "DC"     },
  { name: "Spider-Man",   universe: "Marvel" },
  { name: "Wonder Woman", universe: "DC"     }
];

var areAllDC = true;

for (var i = 0; i < heroes.length && areAllDC; i++) {
  if (heroes[i].universe !== "DC") {
    areAllDC = false;
  }
}

console.log(areAllDC); // false

This approach works fine, but involves extra lines and checks. What if we could do this with one line?

Using Array.prototype.every()

The every() method checks if all elements in the array satisfy a test function. If even one fails, it returns false and stops running.

function isDC(character) {
  return character.universe === "DC";
}

console.log(heroes.every(isDC)); // false

var villains = [
  { name: "Brainiac", universe: "DC" },
  { name: "Sinestro", universe: "DC" },
  { name: "Darkseid", universe: "DC" },
  { name: "Joker",    universe: "DC" }
];

console.log(villains.every(isDC)); // true

Nice and simple, right? Plus, you don’t need to manage flags or stop conditions manually.

Advanced Usage with Index and Array

The callback function for every() can take three arguments: the current element, the index, and the entire array. This allows more complex checks:

function isSameUniverse(el, index, arr) {
  if (index === 0) return true;
  return el.universe === arr[index - 1].universe;
}

console.log(heroes.every(isSameUniverse));  // false
console.log(villains.every(isSameUniverse)); // true

This example checks that each element belongs to the same universe as the one before it.

Browser Support

every() is available in all modern browsers, but not in older versions like IE8 and below. If you need support for old browsers, consider using libraries like Underscore.js, Lodash, or an ES5 shim.

Conclusion

Array.prototype.every() is a clean and elegant way to check if all items in an array meet a condition. It simplifies your code and avoids manual loop logic. Next time you find yourself using a loop just to validate an array, try every() instead!

Post a Comment

Your email address will not be published. Required fields are marked *