JavaScript Array every()

Definition and Usage

every() The method checks if all elements in the array pass the test (provided as a function).

every() The method executes the function once for each element in the array:

  • If a false value returned by the function is found in the array element, every() returns false (and does not check the remaining values)
  • If no false is encountered, every() returns true

Note:every() Does not execute the function for array elements without a value.

Note:every() Does not change the original array.

Instance

Example 1

Check if all values in the age array are 18 or above:

var ages = [32, 33, 16, 40];
function checkAdult(age) {
  return age >= 18;
}
function myFunction() {
  document.getElementById("demo").innerHTML = ages.every(checkAdult);
}

Try it yourself

Example 2

Check if all values in the ages array are or exceed a specific number:

<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p>All ages above minimum? <span id="demo"></span></p>
<script>
var ages = [32, 33, 12, 40];
function checkAdult(age) {
  return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
  document.getElementById("demo").innerHTML = ages.every(checkAdult);
}
</script>

Try it yourself

Example 3

Check if all answer values in the array are the same:

<script>
var survey = [
  { name: "Steve", answer: "Yes"},
  { name: "Jessica", answer: "Yes"},
  { name: "Peter", answer: "Yes"},
  { name: "Elaine", answer: "No"}
];
function isSameAnswer(el, index, arr) {
  if (index === 0){
    return true;
  } else {
    return (el.answer === arr[index - 1].answer);
  }
}
function myFunction() {
  document.getElementById("demo").innerHTML = survey.every(isSameAnswer);
}
</script>

Try it yourself

Browser support

All browsers fully support every() Method:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9.0 Support Support Support Support

Syntax

array.every(function(currentValue, index, arr), thisValue)

Parameter values

Parameters Description
function(currentValue, index, arr) Required. A function to be run for each element in the array.

Function parameters:

Parameters Description
currentValue Required. The value of the current element.
index Optional. The array index of the current element.
arr Optional. The array object to which the current element belongs.
thisValue

Optional. The value to be passed to the function to be used as its "this" value.

If this parameter is empty, the value "undefined" will be passed as its "this" value.

Technical details

Return value: Boolean value. Returns true if all elements in the array pass the test, otherwise returns false.
JavaScript version: ECMAScript 5

Related Pages

Tutorial:JavaScript Array

Tutorial:JavaScript Array Const

Tutorial:JavaScript Array Methods

Tutorial:JavaScript Sort Array

Tutorial:JavaScript Array Iteration