JavaScript: Array.prototype.every

By Xah Lee. Date: . Last updated: .
arrayX.every(f)
Return true if the function f return true for every element. As soon as f return false, exit the iteration and return false. If array is empty, return true.
arrayX can be Array-Like Object.
The function f is passed 3 args: • current_elementcurrent_indexarrayX.
arrayX.every(f, thisArg)
Use thisArg for this Binding of f

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 Array.prototype.forEach]

「every」 on Empty Array

every on empty array returns true.

console.log( [].every(() => false) ); // true
JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

Array

prototype