every() method explained : JS

every() method explained : JS

·

3 min read

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

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;

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;

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

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.

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!