JavaScript: Array.prototype.every

By Xah Lee. Date: . Last updated: .

Returns true if the function f return true for every element. As soon as a element returns false, immediately returns false.

arr must be a array object or array-like object. 〔➤see JavaScript: What's Array-Like Object?

The function f is passed 3 args: array_element, current_index, arr.

If thisVal is given, it is used for this value in f. 〔➤see JavaScript: Keyword “this”

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

var f = function (x) {
    return  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 map version of loop with break. That is, apply a function to every element until one of them returns false.

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

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

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

// prints
// 30
// 2
// false

「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

Array.prototype.every accepts a second argument.

Array.prototype.every(myFunction, thisVal)

The second arg thisVal passed as myFunction's “this” value.

To understand it, see: JavaScript: Keyword “this”

Here's a example:

var f = function () {
    return this.valueOf();
};

console.log(
    [3].every(f, false )
); // false

〔➤see JavaScript: Boolean() Constructor Object

Here's a more practical example:

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

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

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

names.every(addNameToList, adultList);

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

The second arg is useful, typically when you have a method m of a object o, typically with syntax 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.

Reference

ECMAScript 2015 §Indexed Collections#sec-array.prototype.every

ES5 §15#sec-15.4.4.16

Array Topic

  1. JavaScript: Array Basics
  2. JavaScript: Understand JS Array
  3. JavaScript: Create Array
  4. JavaScript: Sparse Array
  5. JavaScript: What's Array-Like Object?
  6. JavaScript: How to Convert Array-Like Object to Array?
  7. JavaScript: Array How-To

  1. JavaScript: Array Object
  2. JavaScript: Array.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.