The every()
method in javascript is used to check if every element in the array satisfies the condition specified in its callback function. This method returns true
if all the elements satisfy the condition or it returns false
immediately if any element does not satisfy the condition.
let numbers = [1, 2, 3, 4];
let check = numbers.every(function(num) {
return num > 0;
});
console.log(check); // true
The every
method executes the callback function once for every element in the array numbers
and checks if the element is greater than 0
. If all the elements are greater than 0
it returns true
.
Let’s look at another example, where the condition does not satisfy.
let numbers = [1, 2, 3, 4];
let check = numbers.every(function(num) {
return num / 2 === 0;
});
console.log(check); //false
Here, we are checking to see if every element in the array numbers
is 2
. The first element does not meet the condition and hence the every```` method returns
false``` immediately.
Once a false condition is encountered, the callback function exists immediately without looping through the remaining elements. To check this let’s make use of the index
parameter.
let numbers = [2, 4, 6, 8, 10];
let check = numbers.every(function(num, i) {
console.log(i);
return num % 2 === 0;
});
console.log(check);
/*
OUTPUT:
0
1
2
3
4
true
*/
Here, we are checking to see if all the elements in the array are divisible by 2
. All the elements in numbers
satisfy this condition and the method returns true
. Now, let’s add an element 7
to this array.
let numbers = [2, 4, 6, 7, 8, 10];
let check = numbers.every(function(num, i) {
console.log(i);
return num % 2 === 0;
});
console.log(check);
/*
OUTPUT:
0
1
2
3
false
*/
As you can see, the every
method exists after the 4th iteration since 7
does not meet the criteria.
The callback function of the every()
also takes a third argument which is the array itself.
let numbers = [2, 4, 6, 8, 10];
let check = numbers.every(function(num, i, arr) {
console.log(i);
console.log(arr);
return num % 2 === 0;
});
console.log(check);
/*
OUTPUT:
0
[2, 4, 6, 8, 10]
1
[2, 4, 6, 8, 10]
2
[2, 4, 6, 8, 10]
3
[2, 4, 6, 8, 10]
4
[2, 4, 6, 8, 10]
true
*/