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

“every” is useful as a forEach with break.

Here's example. Apply f to each element in order. Exit the loop when f returns false.

// Array.prototype.every as loop, exit loop when a item is false

const f = ((x) => {
    if ( x <= 3 ) {
        console.log ( x );
        return true;
    } else {
        return false;
    }

});

[1,2,3,4,5,6].every(f);

// prints
// 1
// 2
// 3

[see JS: Array.prototype.forEach]

「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]

JS Array

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

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials