JavaScript Array every()
Example 1
const ages = [32, 33, 16, 40];
// Create a Test Function
function checkAge(age) {
return age > 18;
}
// Are all ages over 18?
ages.every(checkAge);
More examples below.
Description
The every()
method executes a function for each array element.
The every()
method returns true
if the function returns true for all elements.
The every()
method returns false
if the function returns false for one element.
The every()
method does not execute the function for empty elements.
The every()
method does not change the original array
Array Iteration Methods:
Syntax
Parameters
A function to be run for each element in the array.
The value of the current element.
The index of the current element.
The array of the current element.
undefined
.A value passed to the function as its
this
value.
Return Value
true
if all elements pass the test, otherwise false
.
More Examples
Check if all answers are the same:
{ name: "Steve", answer: "Yes"},
{ name: "Jessica", answer: "Yes"},
{ name: "Peter", answer: "Yes"},
{ name: "Elaine", answer: "No"}
];
let result = survey.every(isSameAnswer);
function isSameAnswer(el, index, arr) {
if (index === 0) {
return true;
} else {
return (el.answer === arr[index - 1].answer);
}
}
Check if all values are over a specific number:
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [32, 33, 12, 40];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.every(checkAge);
}
</script>
Array Tutorials:
Browser Support
every()
is an ECMAScript5 (ES5 2009) feature.
JavaScript 2009 is supported in all browsers since July 2013:
Chrome 23 |
IE/Edge 11 |
Firefox 21 |
Safari 6 |
Opera 15 |
Sep 2012 | Sep 2012 | Apr 2013 | Jul 2012 | Jul 2013 |