Javascript - Array every() Method

The every() method checks if all elements in an array pass a test.

Description

The every() method checks if all elements in an array pass a test.

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

  • If it finds an array element where the function returns a false value, every() returns false and does not check the remaining values
  • If no false occur, every() returns true

every() does not run the function for array elements without values.

every() does not change the original array

Syntax

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

Parameter Values

Parameter Require Description
function(currentValue, index, arr) Required.A function to be run for each element.
thisValue Optional. A 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

For function(currentValue, index, arr),

Argument Require Description
currentValue Required. The value of the current element
index Optional. The array index of the current element
arrOptional. The array object the current element belongs to

Return

A Boolean. Returns true if all the elements in the array pass the test, otherwise it returns false

Example

Check if all the values in the ages array are 18 or over:

Demo

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

function checkAdult(age) {
    return age >= 18;
}

console.log( ages.every(checkAdult));/*www  .ja  va 2  s  .  c o m*/

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

var survey = [
    { name: "A", answer: "Yes"},
    { name: "B", answer: "Yes"},
    { name: "C", answer: "Yes"},
    { name: "D", answer: "No"}
];

function isSameAnswer(el,index,arr) {
    // Do not test the first array element, as you have nothing to compare to
    if (index === 0){
        return true;
    }
    else {
    //do each array element value match the value of the previous array element
        return (el.answer === arr[index - 1].answer);
    }
}

console.log( survey.every(isSameAnswer));

Result