Understanding Array.prototype.every()
What you'll learn: How to use every() to check if all elements in an array satisfy a condition, returning a single true or false result.
The Core Idea
The every() method tests whether all elements in an array pass a test implemented by a provided function. It returns a boolean: true if every single element passes, false if even one element fails.
Think of every() like a quality inspector checking a production line: if every item meets the standard, the batch passes. But if even one item is defective, the entire batch fails inspection.
How It Works
every() takes a callback function that tests each element. The callback should return a truthy or falsy value. The method stops iterating as soon as it finds an element that fails the test (returns false) — it doesn't waste time checking the rest.
const numbers = [2, 4, 6, 8];
const allEven = numbers.every(function(num) {
return num % 2 === 0;
});
console.log(allEven); // true
const mixed = [2, 4, 7, 8];
const allEvenMixed = mixed.every(function(num) {
return num % 2 === 0;
});
console.log(allEvenMixed); // false (stops at 7)
Callback Parameters
Like other array methods you've learned, every()'s callback receives: the current element, its index, and the entire array.
const scores = [85, 90, 78, 92];
const allPassing = scores.every(function(score, index) {
console.log(`Checking index ${index}: ${score}`);
return score >= 75;
});
console.log(allPassing); // true
Empty Arrays
An important quirk: every() returns true for an empty array. This follows mathematical convention — all zero elements vacuously satisfy any condition.
Key Takeaway: Use every() when you need to verify that all elements meet a requirement, returning a simple boolean answer — perfect for validation checks.