ES6 JavaScript
In this ES6 tutorial we are going to learn about the array every method. So, let's get started.
In the previous tutorial we learned about some method.
We use the every method to loop over the elements of the array and it returns true if all the elements satisfy the condition we have defined. Otherwise, we get false.
Let's say we have an array of integers and we want to know if the array contains only even numbers.
Let's see how to solve this problem using for loop.
const arr = [2, 10, 20, 100, 2000];
let foundOdd = false;
for(let i = 0; i < arr.length && !foundOdd; i++) {
if(arr[i] % 2 !== 0) {
foundOdd = true;
}
}
if (foundOdd) {
console.log('found some odd numbers');
} else {
console.log('found only even numbers');
}
We can achieve the same result using every method which simplifies the above code.
const arr = [2, 10, 20, 100, 2000];
const onlyEventNumberExists = arr.every(v => v % 2 === 0);
console.log(evenNumberExists);
Alright, this brings us to the end of this tutorial. Have fun learning.
ADVERTISEMENT