Open In App

JavaScript Array every() Method

JavaScript Array every() method checks if all elements in an array pass a test specified by a function. It returns true if all elements satisfy the condition, otherwise false. Useful for validation or checking conditions on array elements.

Array every() Method Syntax

array.every(callback(element, index, array), thisArg);

Array every() Method Parameters

Array every() Method 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.



Array every() Method Examples

Example 1: Checking If all elements are even or not

Here, the method every() checks if a number is even for every element of the array. Since the array does not contain odd elements therefore this method returns true as the answer.




// 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


Explanation

Example 2: Checking if all elements are positive

Here, the method every() checks if a number is positive for every element of the array. Since the array does not contain negative elements therefore this method returns true as the answer.




// 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


Explanation

Example 3: Checking If one array is exactly the subset of another array

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


Explanation

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers


Article Tags :