Array Every in JavaScript

What is Array Every?

Array Every is a method that exists on the Array.prototype that was introduced in ECMAScript 5 (ES5) and is supported in all modern browsers.

Array Every tells you whether every element in your array passes your test. If every element passes, Every returns true. If just one element in the array fails, Every will return false.

As soon as Every finds a false result, it will short-circuit the loop and continue no more - giving us a performance boost.

Think of Array Every as: “I want to check if every value in my array meets my condition - a yes/no answer”

Here’s the syntax for Array Every:

const returnValue = array.every((value, index, array) => {...}, thisArg);

Our returnValue will contain a Boolean value true or false.

As Every returns a Boolean, its result is commonly used in conditional statements.


Array Every syntax deconstructed:

  • Every’s first argument is a callback function that exposes these parameters:
    • value (the current element)
    • index (the element’s index - not commonly used)
    • array (the array we are looping - rarely used)
    • Inside the body of the function we need to return an expression which will evaluate to a Boolean (true or false), this will then tell Every what to return after completing the loop
  • Every’s second argument thisArg allows the this context to be changed

In its simplest form, here is how Every behaves:

const isEveryValueTrue = [true, true, true].every(Boolean);
// true
console.log(isEveryValueTrue);

As our array contains true values, our expression evaluates to true and Every returns true.

Similarly, by including a false value, Every will return false:

const isEveryValueTrue = [false, true, true].every(Boolean);
// false
console.log(isEveryValueTrue);

As our array contains a false value, it will trigger Every to return false. As a performance benefit, Every will short-circuit and stop the loop on a false test result.

Let’s check some examples out.

Using Array Every

Here’s our data structure that we’ll be using Array Every with (take note of the additional stock property):

const items = [
  { id: '🍔', name: 'Super Burger', price: 399, stock: true },
  { id: '🍟', name: 'Jumbo Fries', price: 199, stock: true },
  { id: '🥤', name: 'Big Slurp', price: 299, stock: false }
];

Our Jumbo Fries '🍟' are out of stock based on the stock: false property.

If an item is out of stock, then we’ll show a message in the console:

const isInStock = items.every((item) => item.stock);

// true
console.log(isInStock);

if (!isInStock) {
  console.log(`Sorry, ${items.find(item => !item.stock).name} is out of Stock.`);
}

Our example here is simple, but real enough. You can see how we’ve used the isInStock resulting variable as part of a conditional statement - where it’s most commonly used!

Notice how simple Every is, we’re returning item.stock (either true or false) to get a final false result.

Give the live Array Every demo a try, you can toggle stock: true to stock: false and see the result change:

Bonus: Every-ing without Every

Let’s check out a for...in loop example that mimics the behaviour of Array Every:

let isInStock = true;

for (let i = 0; i < items.length; i++) {
  const item = items[i];
  if (!item.stock) {
    isInStock = false;
    break;
  }
}

First we set isInStock to true, and we need to disprove otherwise. We’ll loop the items and if one fails, we set isInStock to false. This is the same behaviour as Every, even though we’re inverting the conditional statement.

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, when returned as part of an expression, 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. If you do want items back, Array Map and Array Filter are better methods to use.

Further tips and tricks:

  • Don’t forget to return inside your callback, or your values will be undefined and evaluate to false - avoid undetected bugs!
  • You can access the array you’re looping in the third argument of the callback
  • You can change the this context via a second argument to .every(callback, thisArg) so that any references to this inside your callback point to your object
  • You can use arrow functions with Every but remember that this will be incorrect if you also supply a thisArg due to arrow functions not having a this context
  • Using Every will skip empty array slots as if it were a falsy value
  • You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary

Thanks for reading, happy Everying!


 

#js #javascript 

Array Every in JavaScript
1.05 GEEK