Check with some() and every()
Write a JavaScript function that takes an array of numbers and returns true if the array contains at least one even number (using some()) AND all numbers are positive (using every()). Both conditions must be true.
Array.prototype.some() tests whether at least one element in the array passes the provided function. It returns true immediately upon finding a matching element. Array.prototype.every() tests whether ALL elements in the array pass the provided function. It returns false immediately upon finding a non-matching element. Both methods short-circuit for efficiency.
These methods are the standard JavaScript way to test array conditions without manual loops. They are more declarative and readable than for-loops with flag variables. some() is like a logical OR across elements, while every() is like a logical AND.
Time complexity is O(n) in the worst case, but both methods short-circuit: some() stops at the first true, every() stops at the first false. Space complexity is O(1). The callback receives element, index, and array as arguments.
Edge cases include empty arrays (some returns false, every returns true — vacuously true), arrays with negative numbers, and arrays with zero (zero is neither positive nor negative).
Example Input & Output
All positive but no evens
Has even but not all positive
Has even (2) but NOT all positive
Empty: every returns true but some returns false
Has evens (2,4,6) AND all positive
Algorithm Flow
Solution Approach
Test whether some or all elements of an array pass a condition using some() and every(). some() returns true if at least one element passes. every() returns true if all elements pass. Both stop early on a definitive result.
some() short-circuits on the first true result. every() short-circuits on the first false result. Both are O(n) worst case.
Time O(n), Space O(1).
Best Answers
function solution(nums) {
return nums.some(function(n) { return n % 2 === 0; }) &&
nums.every(function(n) { return n > 0; });
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
