Home JavaScript Higher Order Functions in JavaScript Map, Filter, Reduce and more

Higher Order Functions in JavaScript Map, Filter, Reduce and more

What is Higher Order Function?

A higher order function is a function that takes one or more function as argument or returns a function as its result.

Let’s crack it with an example of a higher order function

Without a higher order function, if I want to add one to each number in an array and display it in the console, I can do the following

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

for (let i = 0; i < array.length; i++) {
console.log(array[i] + 1);
}
}

The function `addOne()` accepts an array, adds one to each number in the array, and displays it in the console. The original values remain unchanged in the array, but the function is doing something for each value.

However, using what may be the most common higher order function, `forEach()`, we can write the whole function in one line.

You Might Be Interested In
``````const numbers = [1, 2, 3, 4, 5];

numbers.forEach((number) => console.log(number + 1));``````

We’ve abstracted the function definition and call in the original code above to just one line. This is what we can do with Higher order functions.

Map, filter and Reduce are all Higher order functions which takes a function as an argument.

Map

• Executes a function on each element of an array.
• Returns a new array with the same length.

When to use Map

If we want to perform the same operation/transformation on each element of the array and get back a new array of the same length with the transformed values.

Let’s understand with an example

``````var numbers=[1,2,3,4,5];

var twiceOfNumbers= numbers.map(n=>n*2);

console.log(twiceOfNumbers);  //[2,4,6,8,10]``````

Filter

• Executes a function on each elements of an array.
• Remove items which don’t satisfy a conditions and returns filtered array.

When to use Filter

If we want to filter out elements from an array, when certain condition is not satisfied then we use filter.

``````var numbers =[1,2,3,4,5];
var greaterThan3=numbers.filter(n=>2);
console.log(greaterThan3);     //[4,5]
``````

Reduce

• We need to declare the initial value of accumulator (final result)
• On each iteration, inside the callback we perform some operation and that will be added to the accumulator.
• Returns a single value as output

When to use Reduce

If we want to executes the callback function on each member of the calling array which results in a single output value.

``````var number=[1,2,3,4,5];
var initialVal=0;
let result =numbers.reduce((accu, val)=>val +accu, initialVal);
console.log(result);  //15
``````

That’s all for this article and with that, it’s a wrap! I hope you found the article useful. Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

Ta da! Having fun learning JavaScript!!