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)
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()()
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) => {})
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
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)
Let's take an example.
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((total, num) => total += num, 0);
sum // 15
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)
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)