In this write-up, we will demonstrate JavaScript functionality to check if all array elements pass a test.
How to Check if All Array Elements Pass a Test in JavaScript?
In JavaScript, every() method checks whether all the elements present in an array satisfy the given function’s condition or not and returns Boolean values as an output. If all the elements satisfy the test, then it returns true, and if even one element does not satisfy the condition, it returns false. Here is the syntax to use every() method in JavaScript.
Syntax:
In the syntax, “array_name” represents the array who’s each element will be iterated over the function defined in the “every()” method.
Example 1: When One or More Array Elements Fail the Test
Let’s practice every() method when one or more array elements do not satisfy the function’s criteria of the every() method.
Code:
tc = x => (x / 3 > 20)
console.log(sal.every(tc))
In this code, we have created an array of numbers. Then, we create a test condition using the arrow function. The test condition divides every array element by 3 and checks if the result after dividing must be greater than 20.
Output:
The output has returned false, which states that at least one array element could not pass the test condition.
Example 2: When All Array Elements Pass the Test
Now, let us see what happens when all the array elements pass the test.
Code:
tc = x => (x / 2 > 5)
console.log(sal.every(tc))
In this code, we create an array of numbers. Then, we create a test condition using the arrow function. The test condition divides every array element by 2 and checks if the result after dividing must be greater than 5.
Output:
The output has returned true which states that all the array elements pass the test condition. Hence, it is concluded that to pass a test for all elements, the condition of every() method must return true.
Conclusion
In JavaScript, we use every() method to check if all the array elements pass a test. The every() method returns a true value if every element passes a test, otherwise it returns a false value. This post has provided a detailed demonstration of every() method to check if all array elements pass a test in JavaScript. Additionally, we have also provided examples in both cases: if all array elements passed the test or any of them failed.