Skip to main content

Command Palette

Search for a command to run...

every() method explained : JS

Published
3 min readView as Markdown
every() method explained : JS
R

19, Hustler.

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.

R

This series is great. Looking forward to more such posts. Keep it up and thanks for sharing it Rahul

2
R
Rahul5y ago

Thank you Rutik.

More from this blog

R

RAHULISM - FrontEnd Web Developer

232 posts

18, Hustler.