Mastering the every() Method in JavaScript
Introduction
The every() method tests whether **all elements** in an array pass a provided test function. It returns true if **every element** meets the condition, and false otherwise. Think of it as a “universal checker” for arrays. ✅
📌 What is every()?
every() runs a callback function on each array element until it finds one that returns false. If it finds such an element, the method immediately stops and returns false. Otherwise, if all pass, it returns true.
- ✔️ Checks if all elements match a condition
- 🚫 Stops early if any element fails
- 🔒 Does not change the original array
💡 Syntax
Basic Syntax
array.every(function(element, index, array) {
// return true or false
}, thisArg)Parameters:
- element — Current array item being processed
- index — (Optional) Index of the current element
- array — (Optional) The original array
- thisArg — (Optional) Value to use as this when executing the callback
🧵 Example: Checking Numbers
Check if all numbers are even
const numbers = [2, 4, 6, 8];
const allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // true📦 Example: String Length Validation
Check string length for all elements
const fruits = ["apple", "banana", "mango"];
const allLong = fruits.every(fruit => fruit.length >= 5);
console.log(allLong); // true🧮 Example: Early Exit Behavior
Stops checking as soon as a condition fails
const nums = [10, 20, 0, 40];
const allPositive = nums.every(n => n > 0);
console.log(allPositive); // false⚠️ Important Notes
Note
- Returns true for an empty array (vacuous truth).
- Does not mutate the original array.
- Useful for validation checks before processing data.
📊 Quick Reference Table
| Example | Output |
|---|---|
| [1, 2, 3].every(n => n > 0) | true |
| [1, -1, 3].every(n => n > 0) | false |
| [].every(n => n > 0) | true |
>>"every() is like an all-or-nothing rule — one failure means total failure."
🔥 Summary
The every() method is perfect for **validating datasets** and ensuring that all items meet certain criteria. It’s efficient, stops early when possible, and keeps your original data intact.