jsguides

Array.prototype.every()

every(callbackFn)

The every() method tests whether all elements in an array pass the condition implemented by the provided function. It returns a boolean value - true if the callback returns truthy for every element, false if any element fails.

This method is useful for validating data, checking permissions, or ensuring all items meet a threshold.

Syntax

every(callbackFn)
every(callbackFn, thisArg)

Parameters

ParameterTypeDefaultDescription
callbackFnfunction-Function to test each element. Receives element, index, and array arguments.
thisArganyundefinedValue to use as this when executing callbackFn.

Callback function arguments

ArgumentTypeDescription
elementanyCurrent element being processed.
indexnumberIndex of the current element.
arrayArrayArray that every() was called on.

Examples

Basic usage

const numbers = [10, 20, 30, 40];

const allPositive = numbers.every(num => num > 0);
console.log(allPositive);
// true

const allOver25 = numbers.every(num => num > 25);
console.log(allOver25);
// false

This also works well with arrays of objects, where the callback inspects a property on each element instead of the element itself. The same logic extends naturally to more complex data structures since the callback has full access to each element.

Validating object properties

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 35 }
];

const allAdults = users.every(user => user.age >= 18);
console.log(allAdults);
// true

String arrays work the same way: the callback receives each string and can call any string method on it. This means you can check prefixes, suffixes, lengths, or any condition expressible as a boolean test on each element. The method stops as soon as any element fails.

Checking array contents

const strings = ["hello", "world", "javascript"];

const allContainH = strings.every(str => str.includes("h"));
console.log(allContainH);
// false - only "hello" contains "h"

const allStartWithLower = strings.every(str => str[0] === str[0].toLowerCase());
console.log(allStartWithLower);
// true

When you need the element’s position in the array, the callback’s second argument provides the index. This is useful for position-dependent checks, such as verifying that elements at even indices meet a specific condition. The third callback argument is the array itself.

With index parameter

const pairs = [2, 4, 6, 8];

// Check if even-indexed elements are even
const valid = pairs.every((num, index) => {
  if (index % 2 === 0) return num % 2 === 0;
  return true;
});
console.log(valid);
// true

One edge case to remember: calling every() on an empty array always returns true. This surprises many developers the first time they encounter it, so check the array length explicitly when an empty input should be treated as invalid.

Empty arrays

const empty = [];
const result = empty.every(x => x > 10);
console.log(result);
// true - vacuous truth: every() returns true for empty arrays

Beyond testing flat arrays of primitives, every() pairs well with Object.values() to validate structured data like form fields. This turns a multi-field validation check into a single expression, which is especially useful in submit handlers. Combined with Object.values(), you can validate an entire form with one call.

Common Patterns

Form validation

const formData = {
  username: "john_doe",
  email: "john@example.com",
  password: "secret123"
};

const isValid = Object.values(formData).every(value => value.length > 0);
console.log(isValid);
// true

For numeric arrays, every() lets you assert that all values fall within a specific range. This pattern is common in sensor data processing and statistical filtering, where out-of-range values need to be caught before analysis. Short-circuiting makes the check efficient for large datasets.

Range checking

const temperatures = [22, 25, 23, 24, 21];

const withinRange = temperatures.every(temp => temp >= 20 && temp <= 30);
console.log(withinRange);
// true

The same approach works for role-based access checks, where you want to confirm every assigned role meets a minimum threshold before granting access to a protected resource or feature. This keeps authorization logic centralized and easy to audit during code review.

Permission checks

const userRoles = ["reader", "commenter"];
const requiredRole = "reader";

const hasAccess = userRoles.every(role => role === requiredRole || role === "admin");
// Returns true if user has at least reader or admin role
console.log(hasAccess);
// true

Short-circuit behavior

every() stops as soon as it finds a failing element — it does not visit the rest of the array. This makes it efficient for large arrays where failure is common. By contrast, filter().length === array.length always processes every element even when the first element fails, so prefer every() for validation checks.

every() on empty arrays

every() returns true for empty arrays — this is called vacuous truth. The reasoning: “every element satisfies the condition” is technically true when there are no elements to contradict it. This is consistent with mathematical logic but can be surprising. If you need to distinguish between “all elements passed” and “there were no elements to test,” check array.length > 0 separately before calling every().

every() vs some()

every() and some() are logical inverses of each other, but not simply negations. every(fn) returns true only if all elements pass; some(fn) returns true if at least one passes. A useful identity: array.every(fn) is equivalent to !array.some(x => !fn(x)). Both short-circuit but in opposite directions — every() exits on the first failure, some() exits on the first success. Choose based on which direction your reasoning flows naturally.

Mutation during iteration

If the callback modifies the array being iterated, behavior follows the same rules as other array iteration methods: elements added after every() starts are not visited, elements deleted before they are reached are skipped (with undefined passed to the callback), and elements modified before they are reached use the modified value. Mutating the array inside the callback is strongly discouraged.

See Also