every() Function is used to check if all the elements of the array satisfies a specific condition.
Let us say, we have a Array that contains five numbers, 5, 8, 2, 81 and 9.
And we want to ensure if all the values in the arrays are less than 10.
Well! There are various ways to do it. But every() gives us an elegant way to do it.
Let us see in the below example.
<html> <body> <script> function numberCheck(i) { return i < 10 } var x = [5, 8, 2, 81, 9] var y = x.every(numberCheck) if (y == true) { document.write("All the numbers in the Array are less tha 10") } else if(y == false) { document.write("No!! Not all the numbers in the Array are less tha 10") } </script> </body> </html>
So, we have an Array that has 5 numbers.
And we want to check, if all the numbers are less than 10. If any of the number is greater than 10 then the execution should stop.
And that's exactly is done with the every() function.
We have defined a function called numberCheck(), that checks if a number is less than 10.
function numberCheck(i) { return i < 10 }
And we have called the above function from every() function.
var y = x.every(numberCheck)
And every() function iterates 5 times(i.e. The length of the array), calling numberCheck() function.
And if at any time it finds a value that is greater than 10, the every() function stops returning false.
And thus we got the below output.
No!! Not all the numbers in the Array are less tha 10
For the if statement.
if (y == true) { document.write("All the numbers in the Array are less tha 10") } else if(y == false) { document.write("No!! Not all the numbers in the Array are less tha 10") }