every method
The every
method checks array
elements according to a passed
function. The method returns true
if the passed function returns true
for all array elements, otherwise the
method returns false
.
You can pass three parameters to the function. If these parameters are present (they are not required), then the first one will automatically get the array element, the second one will get its number in the array (index), and the third one will get the array itself.
Syntax
array.every(function(element, index, array) {
return true or false;
});
Example
We check that all elements in an array of numbers are positive:
let arr = [1, 2, 3, 4, 5];
let check = arr.every(function(elem) {
if (elem >= 0) {
return true;
} else {
return false;
}
});
console.log(check);
The code execution result:
true
Example
Let's check that the product of an element
and its index is always less than 30
:
let arr = [1, 2, 3, 4, 5];
let check = arr.every(function(elem, index) {
if (elem * index < 30) {
return true;
} else {
return false;
}
});
console.log(check);
The code execution result:
true
Example
If necessary, an array itself can be passed to the third parameter:
let check = arr.every(function(elem, index, arr) {
array arr will be available here
});
See also
-
the
some
method
that also allows you to perform an array check -
the
map
andforEach
methods
that allow you to apply a function to each element of an array -
the
reduce
andreduceRight
methods
that reduce an array to a single value