JavaScript Array .every()
method
The JavaScript array .every()
method returns true
if all of the array items passes a condition or test. Otherwise, it will return false.
This array.every()
built-in JavaScript function accepts a callback function that we can use to get every item on each iteration of the array.
The callback function contains the current iterated item, the current index and the copy of the array itself on each iteration.
In simple terms, this method is just looping through all the array items.
Array .every()
Method Syntax
This is how you can use the the .every()
method.
array.every((item, index, array) => {
// run your test here and return a boolean value: true or false
})
Array .every()
Method on Array of Objects
const ninjas = [
{ name: "Uzumaki Naruto", gender: "male", fruit: "🍍" },
{ name: "Hatake Kakashi", gender: "male", fruit: "🍌" },
{ name: "Uchiha Sasuke", gender: "male", fruit: "🍉" },
];
// Example 1: Check whether everyone likes watermelon 🍉
const likesWatermelon = ninjas.every((ninja) => {
return ninja.fruit === "🍉";
});
console.log(likesWatermelon); // the output would be "false"
// Example 2: Check whether all ninjas are male
const areMales = ninjas.every((ninja) => ninja.gender === "male");
console.log(areMales); // the output would be "true"
Based on the given data above, I have an array of objects stored on a variable named ninjas. It contains the name, gender and a favorite fruit of the ninja.
Example 1
: We want to check whether all of the ninjas likes to eat watermelon (🍉). We can achive this using .every()
method. Since not all of the ninja object
with an attribute of fruit
is not equal to 🍉, the output of our code on the console would be: false.
Example 2
: We want to check if all the ninjas are male. Since we are using an arrow function in the callback, we can just do a one-liner code. The output for the second example would be true
because all of ninja.gender
is equal to male
.
Watch Tutorial
Here's a quick video tutorial about the JavaScript array .every()
method.