JavaScript Array Methods: Map, Filter, and Reduce

JavaScript provides powerful built-in array methods to manipulate and transform data cleanly and immutably. Among the most widely used are map(), filter(), and reduce(). Each of these higher-order functions iterates over an array and applies a callback function to its elements. This article explains how each method operates, their specific use cases, and code examples demonstrating their behavior without mutating the original array.


1. The map() Method

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. It always returns a new array with the exact same length as the original.

How It Operates

Example

const numbers = [1, 2, 3, 4, 5];

// Double each number
const doubled = numbers.map(num => num * 2);

console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] (original array remains unchanged)

2. The filter() Method

The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

How It Operates

Example

const numbers = [1, 2, 3, 4, 5, 6];

// Keep only even numbers
const evens = numbers.filter(num => num % 2 === 0);

console.log(evens); // [2, 4, 6]
console.log(numbers); // [1, 2, 3, 4, 5, 6] (original array remains unchanged)

3. The reduce() Method

The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value.

How It Operates

Example

const numbers = [1, 2, 3, 4, 5];

// Sum all values, starting with an initial accumulator value of 0
const sum = numbers.reduce((accumulator, currentVal) => {
  return accumulator + currentVal;
}, 0);

console.log(sum); // 15

Summary Comparison

Method Purpose Return Value Output Array Length
map() Transform each element A new array Equal to the original array
filter() Select elements based on a condition A new array Less than or equal to the original array
reduce() Aggregate elements into a single result Any data type (number, object, etc.) Not applicable (single accumulated value)