JS: Array.prototype.every

By Xah Lee. Date: . Last updated: .
xArray.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.
  • xArray can be Array-Like Object.

f is given 3 args: currentElement currentIndex xArray

xArray.every(f, thisArg)

Use thisArg for this (binding) of f

Example. as Boolean AND Connective

every can be used as a function version of the boolean operator β€œand” &&. γ€”JS: Boolean Operators〕

For example, you have [a,b,c,d] and you want f(a) && f(b) && f(c) && f(d).

// check if every item is greater than 10
console.log([30, 40, 50].every((x) => (x > 10)) );
// true

console.log([30, 2, 50].every((x) => (x > 10)) === false);
// true

Example. as Loop with Break

// using .every as loop, exit loop when f(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

Example. on Empty Array

every on empty array returns true.

console.log([].every((x) => true));
// true

console.log([].every((x) => false));
// true

JavaScript. Array Reduce, Fold

JavaScript. Map, Iteration, Reduce