JavaScript Array.every() And Array.some()

Learn the JavaScript Array.every() and Array.some().
 
Array.every() and Array.some() are Javascript methods that help us to test an array against a specific condition. Firstly we will look at Array.every() and then we will see Array.some().
 

Array.every()

  1. There is a simple concept about Array.every() which is, if every element of array satisfies the condition then Array.every() returns true.
  2. Array.every() takes a callback function as an argument.
Let's check out how Array.every() works,
 
Suppose we have an array which has some numbers like:
  1. let numbers = [1,5,8,2,4,7];  
And we have to check whether this array contains all numbers less than 10 or not. A simple way to check this is to  iterate over every element and compare to 10 and return true or false. But in Array.each() we can do it like this:
  1. function testNumber(element) {  
  2.     return element < 10;  
  3. }  
  4. numbers.every(testNumber)  
  5. // return true  

Array.some()

 
Array.some() is just like Array.every() but as its name suggests if there is any element then it returns true.
 
Since none of the elements in numbers array is greater than 10, its Array.some() returns false. But if we check if any number is greater than 4 then it returns true like this,
  1. function testNumber(element) {  
  2.     return element > 4;  
  3. }  
  4. numbers.some(testNumber)  
  5. // return true;  
We can also use Arrow function with Array.some() and Array.every() like this,
  1. numbers.every( element => element > 10)  
  2. // return true  
Hopefully, you understand. 
 
Thank you.