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 modern browsers since July 2013:

Chrome
23
IE/Edge
10
Firefox
21
Safari
6
Opera
15
Sep 2012 Sep 2012 Apr 2013 Jul 2012 Jul 2013


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.