Menu Home

Array.every()

Hi everyone, and welcome to another R.E.M. (the sleep cycle, not the music group!) edition of Boring JavaScript. Today, we sleep through the Array.every() method. Simply put, it tests each and every item in your array, and will return Boolean True if each entry of the array has a truthy value. But if any one of them has a falsey value, then the method returns Boolean False.

Don’t like to read? Then watch our video.

I Want It All

As stated before, Array.every() will run a test that you supply against every item within the array. If each item returns a truthy value, then Array,every() will return Boolean True. If any single item is a falsey value, then Array.every() returns Boolean False. Let’s take a look at some code:

const animals = [
	{ "type": "Cat", "name": "Fluffy", "class": "Mammalia" },
	{ "type": "Dog", "name": "Fido", "class": "Mammalia"},
	{ "type": "Horse", "name": "Mr. Ed", "class": "Mammalia"},
	{ "type": "Cow", "name": "Betsy", "class": "Mammalia"},
	{ "type": "Coyote", "name": "Wile E.", "class": "Mammalia"},
	{ "type": "Road Runner", "name": "Beep Beep", "class": "Aves"},
	{ "type": "Dolphin", "name": "Flipper",  "class": "Mammalia"},
	{ "type": "Whale", "name": "Moby Dick", "class": "Mammalia"},
	{ "type": "Lizard", "name": "Larry", "class": "Reptilia"}
];

let isMammalia = animals.every( animal => animal.class === "Mammalia" );
console.log(`\nAre all of my animals mammal? ${isMammalia ? "Yes" : "No"}.`);

const mammals = animals.filter( animal => animal.class === "Mammalia" );
isMammalia = mammals.every( animal => animal.class === "Mammalia" );
console.log(`Are all of my mammals mammal? ${isMammalia ? "Yes" : "No"}.`);

Line 13 is our first example. Your job is to pass a callback function as the argument to Array.every(). This callback function will be called on each and every item, and it is to return a ‘truthy’ or ‘falsey’ value. In our case above, we are passed Boolean True or False, as we are using “===”.

Back to the example: Line 13 will check if each item in the array has the “class” property set to “Mammalia”. Once JavaScript gets to Item #5 (Road Runner), the “class” property is “Aves”, which is not equal to “Mammalia”. Since that is a Boolean False, Array.every() will stop at this point and return False back to the variable “isMammalis”. Therefore, we expect the console.log in Line 14 to report “No”.

However, in Line 16 we use Array.filter() to create a new array called “mammals” which contains all the items in “animals” in which the “class” property is equal to “Mammalia”. This means if we run Array.every() against that array (Line 17), every item will pass the test, and Array.every() returns Boolean True. And the console.log in Line 18 should return ‘Yes’.

And here is the output:

Are all of my animals mammal? No.
Are all of my mammals mammal? Yes.

The first line is “No” because the “animals” variable contains at least one item that is not Mammalia, while the second line is “Yes” because all the entries in the variable “mammals” are Mammalia.

No One Lives Here Anymore

What happens on an empty array? No matter what, it will always return True! Let’s look at the code:

const animals = [];

const isMammalia = animals.every( animal => animal.class === "Mammalia" );
console.log(`\nAre all of my animals mammal? ${isMammalia ? "Yes" : "No"}.`);

We can have any function return any type of weird truthy or falsey value, and it won’t matter. If the array tested is empty, Array.every() will always return Boolean True. Here is the output of the above:

Are all of my animals mammal? Yes.

Get On Board the Ark Now!

One thing to remember about Array.every() is that the items to be considered are set before first callback is executed. That means if you add items to your array during the callback process, those items will not be counted. Let’s take a look at some code:

let animalsAdded = 5;
const animals = [
	{ "type": "Cat", "name": "Fluffy", "class": "Mammalia" },
	{ "type": "Dog", "name": "Fido", "class": "Mammalia"},
	{ "type": "Horse", "name": "Mr. Ed", "class": "Mammalia"},
	{ "type": "Cow", "name": "Betsy", "class": "Mammalia"},
	{ "type": "Coyote", "name": "Wile E.", "class": "Mammalia"},
	{ "type": "Dolphin", "name": "Flipper",  "class": "Mammalia"},
	{ "type": "Whale", "name": "Moby Dick", "class": "Mammalia"}
];

const isMammalia = animals.every( animal => {
	if (animalsAdded > 0) {
		animals.push({ type: `Lizard${animalsAdded}`, name: `Lizard${animalsAdded}`, class: 'Reptilia' });
		animalsAdded--;
	}
	return animal.class === "Mammalia";
} );
console.log(`\nAre all of my animals mammal? ${isMammalia ? "Yes" : "No"}.`);
console.log(animals);

The code starts off with the array “animals” having nothing but Mammalia items. However, in the callback function (Lines 13 – 17), we add in five more animals, all of them lizards. So you would expect our output on Line 19 to be “No”, since the last five animals are now “Reptilia”.

But that’s not the case. Let’s see the output:

Are all of my animals mammal? Yes.
[
  { type: 'Cat', name: 'Fluffy', class: 'Mammalia' },
  { type: 'Dog', name: 'Fido', class: 'Mammalia' },
  { type: 'Horse', name: 'Mr. Ed', class: 'Mammalia' },
  { type: 'Cow', name: 'Betsy', class: 'Mammalia' },
  { type: 'Coyote', name: 'Wile E.', class: 'Mammalia' },
  { type: 'Dolphin', name: 'Flipper', class: 'Mammalia' },
  { type: 'Whale', name: 'Moby Dick', class: 'Mammalia' },
  { type: 'Lizard5', name: 'Lizard5', class: 'Reptilia' },
  { type: 'Lizard4', name: 'Lizard4', class: 'Reptilia' },
  { type: 'Lizard3', name: 'Lizard3', class: 'Reptilia' },
  { type: 'Lizard2', name: 'Lizard2', class: 'Reptilia' },
  { type: 'Lizard1', name: 'Lizard1', class: 'Reptilia' }
]

JavaScript says the “animals” are all Mammalia. But that’s not clearly the case, as shown above. And this is correct behavior because Array.every() sets up the items to be tested before the first callback is executed. Basically, it never sees that items have been added during the callback, so as far as it’s concerned, all our items were Mammalia.

Can you delete items during the callback? Actually, yes, and Array.every() will pick it up. However, that’s really a bad practice to get into. Array.every() – and frankly any method anywhere that checks conditionals – relies upon a non-muted variable in which to operate. You don’t want to tell your car mechanic that there’s something wrong, then do a lot of work on it before you give it to the mechanic to trouble-shoot. So don’t change the conditions or the items while doing testing.

The Video

Here is a video on the above blog.

Shameless Plug

Check us out everywhere!

Check out all our videos at: https://www.boringjavascript.com

Check out everything at: https://www.thevirtuoid.com

Facebook: https://www.facebook.com/TheVirtuoid

Twitter: https://twitter.com/TheVirtuoid

YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: