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
| Parameter | Description |
|---|---|
callbackFn | A 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 bycallbackFn.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
- Each element of the array (
12, 18, 25, 30) is checked against the conditionnum > 10. - 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
- The callback function
isEvenchecks if each element is divisible by 2. - All elements in the array are even, so
every()returnstrue.
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
- The custom object
rangeis used asthisin the callback function. - The condition checks if each element is within the range
10to20. - 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
- The second element (
15) satisfies the condition, but the third element (5) does not. - The method immediately returns
falseafter encountering the failing element.
