JavaScript Array every() Method
The every() method iterates over each array element, returning true if the provided function returns true for all elements. It returns false if the function returns false for any element. This method does not operate on empty elements and leaves the original array unchanged.
Syntax
array.every(callback(element, index, array), thisArg);
Parameters
callback
: A function to test each element of the array. It takes three arguments:element
: The current element being processed in the array.index
(optional): The index of the current element being processed.array
(optional): The arrayevery()
was called upon.
thisArg
(optional): An object to usethis
when executing the callback function.
Return value
This method returns a Boolean value true if all the elements of the array follow the condition implemented by the argument method. If any one of the elements of the array does not satisfy the argument method, then this method returns false.
Example 1: This example demonstrates the usage of the every() method on an array to check if every element satisfies a condition defined by the isEven callback function.
// JavaScript code for every() method
function isEven(element, index, array) {
return element % 2 == 0;
}
function func() {
let arr = [56, 92, 18, 88, 12];
// Check for even number
let value = arr.every(isEven);
console.log(value);
}
func();
Output
true
Example 2: This example showcases the utilization of the every() method on an array to verify if all elements meet a condition set by the `isPositive` callback, returning true since all elements are positive.
// JavaScript code for every() method
function ispositive(element, index, array) {
return element > 0;
}
function func() {
let arr = [11, 89, 23, 7, 98];
// Check for positive number
let value = arr.every(ispositive);
console.log(value);
}
func();
Output
true
Example 3: Here, we will check whether one array is exactly the subset of another array or not using several methods like every() as well as includes().
let check_subset = (first_array, second_array) => {
return second_array.every((element) => first_array.includes(element));
};
console.log(
"Subset Condition Satisfies? : " + check_subset([1, 2, 3, 4], [1, 2])
);
console.log(
"Subset Condition Satisfies? : " + check_subset([1, 2, 3, 4], [5, 6, 7])
);
Output
Subset Condition Satisfies? : true Subset Condition Satisfies? : false
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.