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.

myArray must be a array object or array-like object. 〔►see JavaScript: 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 JavaScript: “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 JavaScript: “this” Binding

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

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

// prints

// 1
// false

〔►see JavaScript: 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 JavaScript: Array.prototype.some


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

Array Topic

  1. JavaScript: Array Basics
  2. JavaScript: Understand JS Array
  3. JavaScript: Create Array
  4. JavaScript: Sparse Array
  5. JavaScript: Array-Like Object
  6. 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.