JavaScript ES6 – Array every method

JavaScript array every() is a method that exists on the Array.prototype and was introduced in ECMAScript and is supported in all modern browsers.

JavaScript array every tells you whether every element in your array passes your test. If every element passes it returns true. If just one element in the array fails the test, every method returns false.

Think of JavaScript array every method as: “I want to check if every value in my array meets my condition. yes/no answer!”

array every() parameters

JavaScript array every method consists of following parameters:

  • value – value of current element per iteration
  • index – the element index, not common to use

Let’s see an example on how to use JavaScript array every() method:

        
          let arr = [2, 28, 6];
const result = arr.every((value) => value % 2 === 0);
console.log(result);

// OUTPUT
// true        
      

In above example we checking if every element in arr array is an even number. If all element in array passes our condition value % 2 === 0 then the array every breaks out of the loop and will return true.

In this case we can see 2, 28, and 6 are all even numbertrue is returned as a result.

every() on objects array

We can perform really complex operation using JavaScript array every() method. One of most use cases of JavaScript array every() is using in objects array.

Let’s see an example of every() method for objects:

        
          let people = [
  {
    name: "John",
    age: 16,
  },
  {
    name: "Mary",
    age: 19,
  },
  {
    name: "Bob",
    age: 20,
  }
];
const teenager = people.every((person) => person.age <= 20);
console.log(teenager);

// OUTPUT
// true        
      

In above example we are iteration thru people object array and checking if every person.age <= 20 is  less than or equal to 20?

In this case 16, 19, 20 are smaller than 20, as a result true is returned from every() method.

array every() usage and tips

  • Don’t forget to return values, otherwise it will be undefined
  • If at least one item in array evaluates as false, It exists the loop and return false
  • If all items in array evaluates as true, then the result of every is true
  • It will skip any falsy value and any empty array slots
  • It returns the result as Boolean, no array items value is returned

summary

You’ve now learned how to use array every() to run a test on your array elements. If at least one element in your array evaluates to false then every will exit the loop and return false. If all array elements pass the test every() will return true.

No array items are returned back to you, every is exclusively for returning a Boolean result.

%d bloggers like this: