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

  1. currentElement
  2. currentIndex
  3. arrayX
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 ff = ((x) => (x > 10));

// check if every item is greater than 10
console.log([30, 40, 50].every(ff) === true);
console.log([30, 2, 50].every(ff) === 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 ff = ((x) => {
  if (x <= 3) {
    console.log(x);
    return true;
  } else {
    return false;
  }
});

[1, 2, 3, 4, 5, 6].every(ff);
// 1
// 2
// 3

[see Array.prototype.forEach]

“every” on Empty Array

every on empty array returns true.

[].every(() => false)
BUY ΣJS JavaScript in Depth

JavaScript, Array Reduce, Fold