Follow along with the Exploring JavaScript Array Methods series!
- Exploring Array ForEach
- Exploring Array Map
- Exploring Array Filter
- Exploring Array Reduce
- Exploring Array Some
- Exploring Array Every (you’re here)
- Exploring Array Find
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”
Free eBook
Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.
-
Observables and Async Pipe -
Identity Checking and Performance -
Web Components <ng-template> syntax -
<ng-container> and Observable Composition -
Advanced Rendering Patterns -
Setters and Getters for Styles and Class Bindings
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
returnan expression which will evaluate to a Boolean (trueorfalse), this will then tell Every what to return after completing the loop
- Every’s second argument
thisArgallows the this context to be changed
See the ECMAScript Array Every specification!
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.
Using JavaScript’s
Booleanobject we coerce each result to a Boolean, essentially running an “all-true” check on the array.Booleanis actually a function and typically called asBoolean([1, 2, 3])to coerce any JavaScript value to atrueorfalsevalue.
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.
You can return any type of expression inside Every’s callback function (such as using comparison logic
item.price > 99).
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.
If you are serious about your JavaScript skills, your next step is to take a look at my JavaScript courses, they will teach you the full language, the DOM, the advanced stuff and much more!
Free eBook
Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.
-
Observables and Async Pipe -
Identity Checking and Performance -
Web Components <ng-template> syntax -
<ng-container> and Observable Composition -
Advanced Rendering Patterns -
Setters and Getters for Styles and Class Bindings
Further tips and tricks:
- Don’t forget to
returninside your callback, or your values will beundefinedand evaluate tofalse- avoid undetected bugs! - You can access the array you’re looping in the third argument of the callback
- You can change the
thiscontext via a second argument to.every(callback, thisArg)so that any references tothisinside your callback point to your object - You can use arrow functions with Every but remember that
thiswill be incorrect if you also supply athisArgdue to arrow functions not having athiscontext - 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!
Go to the next article in Exploring JavaScript Array Methods - Array Find!