Array.every()

The Array.every() method in JavaScript tests whether all elements in an array pass a provided test (specified by a callback function). It returns true if all elements pass the test; otherwise, it returns false.

Syntax

</>
Copy
every(callbackFn)
every(callbackFn, thisArg)

Parameters

ParameterDescription
callbackFnA function to test each element in the array. It takes three arguments: element (current element being processed), index (index of the element), and array (the array being traversed).
thisArg (optional)An optional value to use as this when executing callbackFn.

Return Value

The every() method returns a Boolean value:

  • true: If all elements pass the test implemented by callbackFn.
  • false: If at least one element fails the test.

Examples

1. Testing All Elements Greater than a Value

This example checks if all elements in the array are greater than 10.

</>
Copy
const numbers = [12, 18, 25, 30];

const result = numbers.every(num => num > 10);
console.log(result);

Output

true
  1. Each element of the array (12, 18, 25, 30) is checked against the condition num > 10.
  2. Since all elements satisfy the condition, the method returns true.

2. Testing Elements with a Callback Function

Here, a callback function checks if all elements are even numbers.

</>
Copy
const numbers = [2, 4, 6, 8];

function isEven(num) {
  return num % 2 === 0;
}

const result = numbers.every(isEven);
console.log(result);

Output

true
  1. The callback function isEven checks if each element is divisible by 2.
  2. All elements in the array are even, so every() returns true.

3. Using thisArg with a Custom Object

The thisArg parameter allows you to pass a custom object as the this context in the callback function.

</>
Copy
const range = {
  min: 10,
  max: 20
};
const numbers = [12, 15, 19];
const result = numbers.every(function(num) {
  return num >= this.min && num <= this.max;
}, range);
console.log(result);

Output

true
  1. The custom object range is used as this in the callback function.
  2. The condition checks if each element is within the range 10 to 20.
  3. Since all elements meet this condition, the method returns true.

4. Testing Elements When Condition Fails

If any element fails the test, the every() method returns false and stops further iteration.

</>
Copy
const numbers = [10, 15, 5, 25];

const result = numbers.every(num => num > 10);
console.log(result);

Output

false
  1. The second element (15) satisfies the condition, but the third element (5) does not.
  2. The method immediately returns false after encountering the failing element.