Code Logo

Filter Even with Arrow Function

Published at25 Jul 2026
JavaScript Functions Easy 0 views
Like0

Write a JavaScript function that uses an arrow function with the Array.filter() method to extract all even numbers from an array. The filter method creates a new array with all elements that pass a test implemented by the callback function.

The arrow function provides a concise syntax: (num) => num % 2 === 0. This expression checks if a number is divisible by 2 with no remainder. Arrow functions have a shorter syntax than traditional function expressions and automatically return the expression value when written without curly braces.

Array.filter() iterates through each element, passing it to the callback. If the callback returns true, the element is included in the result array. The combination of arrow functions with array methods like filter, map, and reduce is a hallmark of modern JavaScript programming.

Time complexity is O(n) where n is the array length. The filter method visits each element exactly once. Space complexity is O(k) where k is the number of even elements (at most n). The original array remains unmodified.

Edge cases include empty arrays (return empty array), arrays with no even numbers (return empty array), negative numbers, and zero (which is even). The modulo operator handles all integers correctly.

Example Input & Output

Example 1
Input
[-2,-1,0,1,2]
Output
[-2,0,2]
Explanation

Includes zero and negatives

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

No even numbers

Example 3
Input
[1,2,3,4,5,6]
Output
[2,4,6]
Explanation

Filter even numbers

Example 4
Input
[]
Output
[]
Explanation

Empty array

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

All even numbers

Algorithm Flow

Recommendation Algorithm Flow for Filter Even with Arrow Function
Recommendation Algorithm Flow for Filter Even with Arrow Function

Solution Approach

Use an arrow function with filter() to select even numbers from an array. Arrow functions provide a concise syntax: n => n % 2 === 0 replaces the traditional function(n) { return n % 2 === 0; }.

function solution(arr) { return arr.filter(n => n % 2 === 0); }

Arrow functions lexically bind this, making them unsuitable for methods that need the calling context. For simple predicates like parity checking, they provide the most readable syntax.

Time O(n), Space O(n).

Best Answers

javascript - Approach 1
function solution(nums) {
  return nums.filter(function(num) {
    return num % 2 === 0;
  });
}