Code Logo

Check with some() and every()

Published at25 Jul 2026
JavaScript Collections Easy 0 views
Like0

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

Example 1
Input
[1,3,5]
Output
false
Explanation

All positive but no evens

Example 2
Input
[2,-4,6]
Output
false
Explanation

Has even but not all positive

Example 3
Input
[-1,2,3]
Output
false
Explanation

Has even (2) but NOT all positive

Example 4
Input
[]
Output
false
Explanation

Empty: every returns true but some returns false

Example 5
Input
[2,4,6]
Output
true
Explanation

Has evens (2,4,6) AND all positive

Algorithm Flow

Recommendation Algorithm Flow for Check with some() and every()
Recommendation Algorithm Flow for Check with some() and every()

Solution Approach

function solution(nums) {
  return nums.some(function(n) { return n % 2 === 0; }) &&
         nums.every(function(n) { return n > 0; });
}

Best Answers

javascript - Approach 1
function solution(nums) {
  return nums.some(function(n) { return n % 2 === 0; }) &&
         nums.every(function(n) { return n > 0; });
}