目录

JavaScript Array every()

Example 1

Check if all values in ages[] are over 18:

const ages = [32, 33, 16, 40];

ages.every(checkAge)

function checkAge(age) {
  return age > 18;
}
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


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 »

Browser Support

every() is an ECMAScript5 (ES5) feature.

ES5 (JavaScript 2009) fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11