JavaScript Array every() method is used to check whether all elements in an array pass the given test function. It returns true, If all elements pass the test and false otherwise. It doesn’t modify the array.
Syntax
array.every(callback(currentValue, index, arr), thisValue)
Parameters
callback function: It is a function to test for each element in the array. It takes three arguments:
- currentValue(required): The current element being processed in the array.
- index(optional): The index of the current element being processed in the array.
- arr(optional): The array object to the current element belongs.
thisValue(optional): A value is to be passed to the function to be used as its “this” value. If this parameter is empty, the value “undefined” will be passed as its “this” value.
Visual Representation
Example 1: How to Use Array every() method
function isLessThan(element) {
return element < 100;
}
let arr = [12, 10, 44, 78, 96]
let check = arr.every(isLessThan);
console.log(check);
Output
true
Example 2: Using Arrow function
let arr = [12, 10, 44, 78, 96]
const greterThan = (currentValue) => currentValue > 50
console.log(arr.every(greterThan))
const allEven = (currentValue) => currentValue % 2 === 0
console.log(arr.every(allEven))
Output
false
true
Example 3: Using sparse arrays
This function will not run its predicate on empty slots.
console.log([, 10, , 78, 96].every((x) => x !== undefined));
console.log([12, 10, , 78, 96].every((x) => x === 2));
Output
true
false
Example 4: Passing non-array objects
const arrayLike = {
length: 3,
0: "r",
1: "c",
2: "b",
};
console.log(
Array.prototype.every.call(arrayLike, (x) => typeof x === "string"),
);
Output
true
Example 5: Using with includes() Method
The following code checks if all the elements of an array are present in another array using the array.every() and array.includes() methods.
const isSubset = (array1, array2) =>
array2.every((element) => array1.includes(element));
console.log(isSubset([12, 10, 44, 78, 96], [10, 96]));
console.log(isSubset([12, 10, 44, 78, 96], [90, 12, 7]));
Output
true
false
Browser compatibility
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1.5 and above
- Safari 3 and above
- Opera 9.5 and above