JS Built-ins
← Array52 / 226
ArrayArray.prototype.everybeginner

Array.prototype.every() β€” check all positive

πŸ“– Usage Example
const nums = [2, 4, 6, 8]
nums.every(n => n > 0)  // β†’ true
nums.every(n => n > 5)  // β†’ false

Use every() to check whether all elements in an array satisfy a condition.

Array.prototype.every()

Array.prototype.every(callback) returns true if the callback returns a truthy value for every element, and false as soon as any element fails the test. It short-circuits on the first failing element.

Challenge: Implement allPositive(nums) that returns true if every number in the array is greater than 0.

allPositive([1, 2, 3])    // β†’ true
allPositive([1, -1, 3])   // β†’ false
πŸ’‘ Hints (2)
  • β€’ `every()` short-circuits β€” it stops as soon as it finds a failing element.
  • β€’ An empty array always returns `true` with `every()` β€” this is called vacuous truth.