JavaScript: Array.prototype.every Example

By Xah Lee. Date: . Last updated: .

every is a function, and is a property of Array.prototype object.

Syntax:

arr.every(f) → return true if the function f return true for every element. As soon as a element returns false, every 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, the_array.

arr.every(f, thisVal) → passes thisVal for this value in f. 〔➤see JavaScript: Keyword “this”

ES5 §15#sec-15.4.4.16

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.

back to JavaScript: Array Methods

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.