Javascript Array every()

Introduction

The every() method tests whether all array elements pass the test.

The test is implemented by a function.

The every() method returns a Boolean value.

Calling every() method on an empty array will return true for any conditions.

arr.every(callback(element[, index[, array]])[, thisArg])
Parameter
Optional
Meaning
callback




Not




A function to test for each element.
It takes three arguments:
element - current element being processed in the array.
index - Optional, index of the current element being processed.
array - Optional, the whole array.
thisArg Optional
A value to use as this when executing callback.

The every() method returns true if the callback function returns a truthy value for every element.

Otherwise, false.

The every() method executes the callback function once for each array element.

It runs until it finds the one where callback returns a falsy value.

The every method immediately returns false on a falsy result.

callback is invoked only for array indexes with assigned values.

every() method does not change the array on which it is called.

The following example tests whether all elements in the array are bigger than 10.

function isBigEnough(element, index, array) {
  return element >= 10;
}
let a = [1, 5, 8, 13, 4].every(isBigEnough);  
console.log(a);//from   w w w  .  j a va2 s  .c  o m
a = [12, 54, 18, 130, 44].every(isBigEnough); 
console.log(a);

Arrow functions provide a shorter syntax for the same test.

let a = [12, 5, 8, 10, 4].every(x => x >= 10);   
console.log(a);//from   w  ww.ja v a2s  . c  o m
a = [12, 4, 1, 10, 4].every(x => x >= 10); 
console.log(a);

The following examples shows the behaviour of the every() method on modified array.

The range of elements processed by every() is set before the first invocation of callback.

Elements appended to the array after the call to every() begins will not be visited by callback.

// Modifying items
let arr = [1, 2, 3, 4];
arr.every( (elem, index, arr) => {//from w w w. j  a  va  2 s  .  co m
  arr[index+1] -= 1
  console.log(`[${arr}][${index}] -> ${elem}`)
  return elem < 2 
});
console.log(arr);

More example:

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];

let everyResult = numbers.every((item, index, array) => item > 2);
console.log(everyResult); // false 

let someResult = numbers.some((item, index, array) => item > 2);
console.log(someResult); // true 



PreviousNext

Related