Home »
JavaScript »
JavaScript Examples
How to check a condition with all array elements in JavaScript?
By IncludeHelp Last updated : January 21, 2024
Problem statement
Given a JavaScript array, you have to check a condition with all array elements i.e., the all elements of the array are satisfying a given condition or not.
Checking a condition with all array elements
To a condition with all array elements, create a callback function by checking the specific condition and then use the Array.every() method by passing the callback function. It will return true if all elements satisfy the condition; false, otherwise.
JavaScript code to a condition with all array elements
The below example checks whether all elements of arrays (arr1 and arr2) are greater than or equal to 20.
// creating a callback function
function checkElementSize(element, index, array) {
return element >= 20;
}
// creating two arrays
arr1 = [20, 40, 60, 80];
arr2 = [50, 60, 70, 18];
// calling functions & printing results
console.log(arr1.every(checkElementSize));
console.log(arr2.every(checkElementSize));
Output
The output of the above code is:
true
false
To understand the above example, you should have the basic knowledge of the following JavaScript topics: