every()
ES5+Tests whether all elements in the array pass the test implemented by the provided function.
Syntax
array.every(callback(element, index, array), thisArg)Parameters
callback Function Function to test each element
Return Value
true if all elements pass the test
Examples
const numbers = [2, 4, 6, 8];
const allEven = numbers.every(x => x % 2 === 0);
console.log(allEven); 📌 When to Use
Use every() when you need to verify that ALL elements in an array satisfy a condition. Ideal for validation scenarios, ensuring data integrity, or checking if all items in a collection meet requirements.
⚠️ Common Mistakes
Forgetting that every() returns true for empty arrays - add an explicit length check if needed
Using every() when you want to count matches - use filter().length instead
Confusing every() with some() - every() requires ALL elements to match
✅ Best Practices
Add arr.length > 0 && arr.every(...) if an empty array should return false
Use for comprehensive validation: allFieldsValid && every(field => field.value)
Combine with type guards in TypeScript: arr.every((x): x is ValidType => isValid(x))
⚡ Performance Notes
every() short-circuits and returns false immediately when it finds a falsy result. This makes it very efficient for validation - it stops checking as soon as one element fails. However, for finding which element failed, you'll need find() or filter().
🌍 Real World Example
Checking All Permissions Before Action
Verify that a user has all required permissions before allowing an action
const requiredPermissions = ['read', 'write', 'delete'];
const userPermissions = ['read', 'write', 'delete', 'admin'];
const hasAllPermissions = requiredPermissions.every(
permission => userPermissions.includes(permission)
);
// hasAllPermissions: true
if (hasAllPermissions) {
performAdminAction();
} else {
showAccessDenied();
}