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 a decision depends on ALL elements passing a test: every form field valid before enabling the submit button, every file under the size limit before starting an upload, every permission present before revealing an admin panel, every line item in stock before confirming an order. It reads exactly like the requirement it implements, which is why validation and precondition code is its home turf. The choice between every() and its dual is mechanical: every(cond) demands universal compliance, some(cond) demands a single witness, and each can be rewritten as the negation of the other - !arr.some(x => !cond(x)) is every(), a rewrite worth doing whenever the positive predicate is the more natural one to name. Prefer every() over filter(cond).length === arr.length, which scans everything and allocates an array merely to compare two numbers. The one behavior that regularly surprises people is vacuous truth: every() on an empty array returns true, because no element violates the condition. That is mathematically correct and usually harmless, but any rule of the form "all items must be valid" silently approves zero items - pair it with a length check when emptiness itself is invalid.
⚠️ Common Mistakes
Overlooking vacuous truth: every() on an empty array is always true, per the ECMAScript spec. A checkout guard like items.every(isInStock) therefore lets an empty cart sail through, and a permissions rule approves a user with zero roles. Whenever "no items" should mean "not allowed", write arr.length > 0 && arr.every(...) explicitly.
Using every() when the code actually needs to know how many or which elements failed. every() is a black box that answers pass/fail and short-circuits on the first failure, so it cannot power an error summary like "3 fields are invalid" - that job needs filter() to collect the failures, with every() optionally kept as the cheap fast-path check.
Confusing every() with some(). The two invert each other: every() fails fast on the first counterexample, some() succeeds fast on the first witness. Tests written against homogeneous fixtures (all valid or all invalid) cannot tell them apart, so the swap survives CI and detonates on the first mixed dataset in production.
Passing an async predicate. Every call of an async function returns a Promise, and Promises are truthy, so arr.every(async x => await validate(x)) returns true for any array without waiting for a single validation. Run the checks with Promise.all() first, then call every() on the resolved booleans.
Relying on truthy returns with values that are legitimately falsy. fields.every(f => f.value) rejects a checkbox whose value is false and a quantity of 0 even though both are valid inputs. Compare against what "invalid" really means: f.value !== undefined && f.value !== "".
✅ Best Practices
Decide consciously what an empty collection should mean for each rule, and encode it: arr.length > 0 && arr.every(...) when emptiness is failure, plain every() when emptiness is acceptable. Leaving the decision implicit is how "submit empty form" bugs are born.
Structure validation as small named predicates combined by every(): fields.every(isFilled) && files.every(isUnderLimit). Each rule stays independently testable, and the top-level expression reads like the acceptance criteria it implements - reviewers can verify it against the spec at a glance.
In TypeScript 5.5+, a type-guard predicate lets every() narrow the whole array: if (arr.every((x): x is string => typeof x === "string")) treats arr as string[] inside the branch, eliminating casts in code that first validates and then processes.
When a failed check needs explanation, run the inverse query for reporting: const failures = items.filter(x => !isValid(x)). Use every() as the fast gate and reach for the detailed scan only on the failure path, so the common success case stays cheap.
Put the most likely-to-fail condition first in compound predicates. every() bails at the first false, so checking the cheap, frequently-violated rule before the expensive rare one minimizes work on the typical invalid input.
⚡ Performance Notes
every() short-circuits on the first falsy callback result, so invalid data is detected almost for free - the expensive case is ironically the fully valid array, which requires the complete O(n) sweep with one callback invocation per element. No allocation happens either way, making every() as cheap as this check can be expressed with array methods; only a hand-rolled for loop avoids the per-element function-call overhead, a difference V8 largely erases for small monomorphic callbacks through inlining. Two scale considerations: first, validation that runs on every keystroke should debounce or validate only the changed field, because re-sweeping a 200-field form 60 times a second is wasted work regardless of how fast each sweep is; second, when the predicate itself is costly (regex, Date parsing, deep object access), hoist invariant work out of the callback or precompute derived fields once, since every() gives the predicate no caching for you. Like some(), it skips holes in sparse arrays.
🌍 Real World Example
Checking All Permissions Before Action
Authorization checks are naturally universal conditions - missing even one required permission must deny the action - which makes every() the precise operator. Here the requirements list drives the check: for each required permission, includes() confirms the user holds it. Note the direction of iteration: it is requiredPermissions.every(...), not userPermissions.every(...), because extra user permissions are fine while missing required ones are not; reversing the arrays is a classic logic slip. For larger permission sets, converting userPermissions to a Set turns each membership test O(1). The same pattern gates deployments (all checks green) and bulk operations (all rows valid).
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();
}