JS: Array.prototype.every
xArray.every(f)
-
- Return
true
if the function f returntrue
for every element. As soon as f returnfalse
, exit the iteration and returnfalse
. - If array is empty, return
true
. - xArray can be Array-Like Object.
f is given 3 args: currentElement currentIndex xArray
- Return
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