JS: 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.

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

var f = function (x) {
    return  x > 10 ;

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

    [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.

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

function f (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
        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();

    [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

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

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

names.every(addNameToList, adultList);

); // ["John", "Jane", "Mary"]


〔►see JS: Array.prototype.some


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
Like what you read? Buy JavaScript in Depth