Understanding JavaScript’s map(), filter(), and reduce() functions

supraja
2 min readFeb 12, 2024

--

image credit: link

JavaScript provides powerful array methods like map(), filter(), and reduce() that allow for efficient and concise manipulation of array elements.

In this blog post, we’ll explore each of these functions, understand how they work, and examples to illustrate their usage.

(1) map():

The map() function applies a provided callback function to each element in an array and returns a new array containing the results.

Example:

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]

(2) filter():

The filter() function creates a new array with all elements that pass the test implemented by the provided callback function.

Example:

const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4]

(3) reduce():

The reduce() function applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Example:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15

In this example, 0 is provided as the initial value of the accumulator (acc). This means that the sum starts at 0, and then each element of the numbers array is added to it sequentially. If you omit the initial value, the first element of the array will be used as the initial value of the accumulator.

In summary, map(), filter(), and reduce() are powerful tools for working with arrays in JavaScript, allowing for easy manipulation and transformation of array elements.

--

--