iteration
Array.prototype.every
Returns true only if the callback returns truthy for every element, short-circuiting on the first falsy result. Reach for it to validate that all items meet a condition.
arr.every(callbackFn[, thisArg]) Parameters
| Parameter | Purpose |
|---|---|
| callbackFn(element, index, array) | Predicate tested against each element |
| thisArg | Value used as `this` inside callbackFn |
Examples
console.log([2,4,6].every(n => n % 2 === 0)); Logs: true
console.log([2,4,7].every(n => n % 2 === 0)); Logs: false
console.log([].every(() => false)); Logs: true (empty arrays are vacuously true)
console.log([{ok:true},{ok:true}].every(o => o.ok)); Logs: true
Gotcha
every on an empty array is TRUE (vacuous truth). Combine with `.length > 0` if that semantic is wrong for you.
Related methods
Array.prototype.some
Returns true if the callback returns truthy for at least one element, short-circuiting on the first hit. Reach for it to answer "does anything match?" without walking the full array.
Array.prototype.filter
Creates a new array containing every element for which the callback returned a truthy value. Reach for it to pare a list down to items matching a predicate.
Array.prototype.includes
Returns true if the array contains searchElement using SameValueZero equality (ES2016). Reach for it as the readable boolean alternative to `indexOf(x) !== -1`.
Array.prototype.forEach
Executes a provided callback once for each array element, in ascending order. Reach for it when you need side effects (logging, DOM updates, pushing to another store) and do not need a return value.
Array.prototype.map
Creates a new array populated with the results of calling a callback on every element of the calling array. Reach for it whenever you want to transform each element 1-to-1 into a new value.