JS: Array.prototype.every

By Xah Lee. Date: . Last updated: .

Return true if the function f return true for every element.

If myArray is empty, return true.

This is done by evaluating f on each element in array in order. As soon as f(item) return false, exit the iteration and return false.

myArray must be a array object or array-like object. [see JS: Array-Like Object]

The function f is passed 3 args: • current_elementcurrent_indexmyArray.

If thisArg is given, it will be used as this value of f. If it is not given, undefined is used.

[see JS: “this” Binding]

Use “every” as Boolean “AND” Connector

Array.prototype.every can be used as a function version of the boolean operator “and” &&.

For example, you have [a,b,c,d] and you want f(a) && f(b) && f(c) && f(d)].

// example of Array.prototype.every

const f = ((x) => (x > 10)) ;

// check if every item is greater than 10
console.log( [30 , 40, 50].every(f) ); // true

console.log( [30 , 2, 50].every(f) ); // false

Use “every” as Loop with Break

Array.prototype.every can also used as a forEach with break. That is, apply a function to every element until one of them returns false.

[see JS: Array.prototype.forEach]

// example of Array.prototype.every
// showing exit immediatly when a item is false

const f = ((x) => {
    console.log(x);
    return x > 10 ;
});

// check if every item is greater than 10
[30 , 2, 50].every(f); // returns false

// prints
// 30
// 2

「every」 on Empty Array

every on empty array returns true.

// every on empty array returns true
console.log(
    [].every(
        function () {return false;}
    )
); // true

Using the Second Argument

myArray.every(f, thisArg) → use thisArg as “this” value for f.

[see JS: “this” Binding]

function f ( x ) {
    console.log ( x );
    return this.valueOf();
}

console.log(
    [1,2,3,4].every(f, false )
);

// prints

// 1
// false

[see JS: Boolean Object]

The second arg is useful when you have a method m of a object o, and typically you write o.m(x) that does something to o. Now, you want to use this method in every, but you want to pass a different object to m.

Here's a more practical example:

// example of Array.prototype.every with second argument

const names = ["John", "Jane", "Mary"];
const adultList = [];

function addNameToList (name) {
    this.push(name);
    return true;
 };

names.every(addNameToList, adultList);

console.log( adultList );
// ["John", "Jane", "Mary"]

Array.prototype.some

[see JS: Array.prototype.some]

Reference

ECMAScript® 2016 Language Specification#sec-array.prototype.every

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth