DEV Community

Soumak Dutta
Soumak Dutta

Posted on

Understanding higher-order functions with map & reduce in JavaScript

Higher Order Functions

Higher order functions are a hot topic in functional programming. It's used by most of us without knowing it. So in this article, I will clear all confusion about higher-order functions.

In JavaScript functions are treated as objects. They can be assigned to a variable, passed as a parameter and returned from a function. So we called them first-class objects.

So, A higher-order functions are functions that received functions as a parameter or return functions as output.

That means we can pass a function as a parameter to another function. Like..

const foo = call => call();

const sayHi = () => "hi";

foo(sayHi)
Enter fullscreen mode Exit fullscreen mode

Here we pass sayHi function to foo function as an argument. This approach is also called callback.

Also we can return function as output. Like..

const foo = () => () => "Hi";

foo()()
Enter fullscreen mode Exit fullscreen mode

Here we return an anonymous function from function foo.

Now we have understood higher-order functions, we could learn some higher order functions built into Javascript.

Map

The map is an higher order array function. It takes a callback function and the function will called for each element in the array. It will return an entirely new array.

Syntax of map function.

array.map((current, index, array) => {})
Enter fullscreen mode Exit fullscreen mode

Let's take an example.

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

const newArr = arr.map(num => num * 2);

newArr  // 2, 4, 6, 8, 10
Enter fullscreen mode Exit fullscreen mode

Here we call the function for each number and return the number multiplying 2 with it.

Note: Map doesn't change the actual array. Instead it creates a new array with modified values.

Reduce

Reduce is also a higher order function. But unlike map it call the callback for each element and return a single reduced value.

Syntax of reduce function.

array.reduce((accumulator, current, index, array) => {}, initialValue)
Enter fullscreen mode Exit fullscreen mode

Let's take an example.

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

const sum = arr.reduce((total, num) => total += num, 0);

sum  // 15
Enter fullscreen mode Exit fullscreen mode

Here, we find the sum in a list of numbers. Sum is the accumulator. We initialize it with 0 and return the sum.

We can make use of the accumulator to calculate any type of value in an array.

We can calculate the minimum number from a list. Like..

const are = [5,7,3,9,6,3];

const minimum = arr.reduce((min,num) => min < num ? min : num)
Enter fullscreen mode Exit fullscreen mode

So, use map if you want to modify each element in an array. And use reduce when you want to reduce the array to a single value.

I hope you learn something new in this article. Thanks for reading.

Top comments (0)