The Every Method: Testing All Elements
You'll learn how to use Array.every() to check whether all elements in an array satisfy a condition.
What Is every()?
The every() method tests whether all elements in an array pass a test function you provide. It returns a single boolean: true if every element passes, false if even one element fails.
Think of it like a quality inspector checking every item on an assembly line. If all items pass inspection, the whole batch is approved. But if any single item fails, the entire batch is rejected.
How It Works
every() calls your test function on each element. As soon as any element returns false, every() stops checking (short-circuits) and returns false. Only if all elements pass does it return true.
const scores = [85, 92, 78, 95];
const allPassed = scores.every(score => score >= 70);
console.log(allPassed); // true (all scores are 70+)
const allPerfect = scores.every(score => score >= 90);
console.log(allPerfect); // false (78 and 85 are below 90)
The Callback Signature
Like map, filter, and reduce, the callback receives three parameters:
const numbers = [2, 4, 6, 8];
const allEven = numbers.every((element, index, array) => {
return element % 2 === 0;
});
console.log(allEven); // true
Common Use Cases
Validation is a classic scenario:
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 17 }
];
const allAdults = users.every(user => user.age >= 18);
console.log(allAdults); // false (Charlie is 17)
Key Takeaway: Array.every() returns true only if all elements pass your test function; it short-circuits on the first failure, making it efficient for validation checks.