The Array.every()
method is a built-in JavaScript function used to test whether all elements in an array pass a specified condition implemented by a callback function. It returns a boolean value: true
if all elements satisfy the condition, and false
otherwise.
Syntax
arr.every(callback(element, index, array), thisArg);
Parameters
Parameter | Description |
---|---|
callback | (Required) A function that tests each element of the array. |
element | (Required) The current element being processed in the array. |
index | (Optional) The index of the current element being processed in the array. |
array | (Optional) The array every() was called on. |
thisArg | (Optional) A value to use as this when executing the callback function. Defaults to undefined . |
Return Value
The every()
method returns –
true
if the callback function returnstrue
for every array element.false
if the callback function returnsfalse
for at least one array element.
Example 1: Checks all elements in the array are even numbers.
let arr = [2, 4, 6, 8]; let result = arr.every(num => num % 2 === 0); console.log(result); // Output: true
Example 2: The every() method verifies that every string in the array has more than 2 characters.
let arr = ['apple', 'banana', 'cherry']; let result = arr.every(word => word.length > 2); console.log(result); // Output: true
Example 3: Using with Objects – checks whether all users are active.
let users = [ { id: 1, name: 'John', isActive: true }, { id: 2, name: 'Alice', isActive: true }, { id: 3, name: 'Bob', isActive: false } ]; let allActive = users.every(user => user.isActive); console.log(allActive); // Output: false
Example 4: Handling Empty Arrays – The every() always returns true because there are no elements to violate the condition.
let emptyArray = []; let result = emptyArray.every(num => num > 0); console.log(result); // Output: true
Example 6: The thisArg
parameter binds the context
object to the callback function.
let context = { minAge: 18 }; let ages = [20, 25, 30]; let allAdults = ages.every(function(age) { return age >= this.minAge; }, context); console.log(allAdults); // Output: true
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1.5+ |
Safari | 3+ |
Edge | 12+ |
Opera | 9.5+ |
Internet Explorer | 9+ |