DEV Community

Cover image for every() method explained : JS
Rahul
Rahul

Posted on

every() method explained : JS

The every() method tests whether all elements in the array pass the test implemented by the provided function. The result of the every() method is a boolean. Let's see the syntax:-

const new = array.every(v, i, a) => {
     // return boolean
});

// new - the boolean that is returned
// array - the array to run the reduce function on. 
// v - the current value being processed
// i - the curret index of the value being processed
// a - the original array
Enter fullscreen mode Exit fullscreen mode

The every() method can be thought of like a for loop, that is specifically for checking values. Take a look at this example:-

const nums = [11, 12, 13, 14];
let alBelowtwenty = true; 
for(let i = 0; I< nnums.length; i++) {
    if(allBelowTwenty) {
    allBelowTwenty = nums[i] < 20; 
   }
}
   // allBelowTwenty = true; 

Enter fullscreen mode Exit fullscreen mode

This code results in a boolean, the results of the implemented test. Yes, it works, but there is an easier and better way to get the same result.

Rewriting the previous function using the every() method.

const nums = [11, 12, 13, 14];
const allBelowTwenty = nums.every(value => value < 20); 

// allBelowTwenty = true; 
Enter fullscreen mode Exit fullscreen mode

Just See. No loop needed!

And using the arrow function we have a nice and clean function to create the same array. Because we only use the value, we only pass that to the map() method.

Now let's see another example:-

const nums = [11, 12, 13, 14]; 
const nums2 = [0, -1, -77, 15];

nums.every( value => value > 0 ); 
  // returns true
nums2.every( value => value > 0 ); 
  // returns false
Enter fullscreen mode Exit fullscreen mode

The second statement returns false because not every item in the nums2 array is bigger than 0.



I'm done!
Read more;-

Thanks For Reading. If you have anything going on your mind comment down below.

Top comments (2)

Collapse
 
hb profile image
Henry Boisdequin

Wow, well explained. I've never even heard of the every() method!

Collapse
 
rahxuls profile image
Rahul

Now you did. Thanks.