JavaScript Array every()
Example 1
// Create an Array
const ages = [32, 33, 16, 40];
// Create a Test Function
function checkAge(age) {
return age > 18;
}
// Are all ages over 18?
ages.every(checkAge);
Try it Yourself »
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
array.every(function(currentValue, index, arr), thisValue)
Parameters
Parameter | Description |
function() | Required. A function to be run for each element in the array. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
Return Value
Type | Description |
Boolean |
true if all elements pass the test, otherwise false . |
More Examples
Check if all answers are the same:
const survey = [
{ 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);
}
}
Try it Yourself »
Check if all values are over a specific number:
<p><input type="number" id="ageToCheck" value="18"></p>
<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>
Try it Yourself »
Array Tutorials:
Browser Support
every()
is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) is fully supported in all modern 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 |