Higher Order Functions in JavaScript – Explained With Practical Examples
Higher Order Functions in JavaScript – Explained With Practical Examples
Forum Donate
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 1/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
There are several different types of higher order functions like map
and reduce. We will discuss these later in this tutorial. But before
that let's first dive deep into what higher order functions are.
higherOrderFunction(callbackFunction);
The above example is quite simple isn't it? So let's expand it further
and see how you can use HOFs to write more concise and modular
code.
So, suppose I want you to write a function that calculates the area Donate
Forum
and diameter of a circle. As a beginner, the first solution that comes
Learn to code — free 3,000-hour curriculum
to our mind is to write each separate function to calculate area or
diameter.
console.log(calculateArea(radius));
console.log(calculateDiameter(radius))
But have you noticed the problem with the above code? Aren't we
writing almost the same function again and again with slightly
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 3/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
So, let's see how we can write the same code using HOFs:
console.log(calculate(radius, area));
console.log(calculate(radius, diameter));
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 4/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
Now, as you can see in the above code, we have only written a single
Forum Donate
The code that we have written using HOFs is concise and modular.
Each function is doing its own job and we are not repeating anything
here.
console.log(calculate(radius, circumeference));
When working with arrays, you can use the map() , reduce() ,
filter() , and sort() functions to manipulate and transform data
in an array.
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 5/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
When working with functions, you can use the compose() function
to create complex functions from simpler ones.
The callback function that is being passed to map uses the arrow
function syntax, and it takes a single argument num . This function
adds 10 to num (every element in the array) and returns the result.
const users = [
{firstName: 'John', lastName: 'Doe', age: 25},
{firstName: 'Jane', lastName: 'Doe', age: 30},
{firstName: 'Jack', lastName: 'Doe', age: 35},
{firstName: 'Jill', lastName: 'Doe', age: 40},
{firstName: 'Joe', lastName: 'Doe', age: 45},
]
We are mapping over each user using the map() method to extract
the properties firstName and lastName .
Forum
The filter() function takes an array and returns a new array withDonate
only the values that meet certain criteria. It also does not mutate
Learn to code — free 3,000-hour curriculum
the original array. It is often used to select a subset of data from an
array based on certain criteria.
Example 1: You can use filter() to return only the odd numbers
from an array of numbers.
Example 2: You can use filter() to return only the users having
age greater than 30 in an array.
const users = [
{firstName: 'John', lastName: 'Doe', age: 25},
{firstName: 'Jane', lastName: 'Doe', age: 30},
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 8/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
But don't worry – here, we will learn it through quite a few examples
and I will try my best to make you understand this method.
Now, one doubt that might comes to your mind is why we use the
reduce() method. As there are already lots of methods, how can
we decide which one to use and when?
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 9/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
Forum
In the case of the reduce() method, you should is used it when youDonate
want to perform some
Learn operation
to code — free on the elements
3,000-hour of an array and
curriculum
return a single value as a result. The "single value" refers to the
accumulated result of repeatedly applying a function to the
elements of a sequence.
For example, you might use reduce() to sum up all the elements in
an array, to find the maximum or minimum value, to merge multiple
objects into a single object, or to group different elements in an
array.
console.log(sum); // 15
Forum Donate
In each iteration, the function adds the current value to the total
Learn
and returns the newtovalue
codeof
— the
freetotal.
3,000-hour curriculum
The reduce() method then uses the returned value as the total
for the next iteration, until it has processed all the elements in the
array.
Finally, it returns the final value of the total, which is the sum of all
the elements in the array.
In this example, again we have two arguments max and curr in the
callback function. Notice we haven't passed the second parameter
in the reduce() method this time. So, the default value will be the
first element in the array.
In this case, the reduce() method will start by setting max to 5 and
curr to 20. It will then check if 20 is greater than 5, which it is, so it
updates max to 20.
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 11/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
It will continue this process until it has processed all the elements in
the array. The final value of max will be the maximum value in the
array, which is 100 in this case.
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const obj3 = { e: 5, f: 6 };
const mergedObj = [obj1, obj2, obj3].reduce((acc, curr) => {
return { ...acc, ...curr };
}, {});
console.log(mergedObj); // { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }
The function uses the spread operator ( ... ) to create a new object
that combines the properties of the current merged object acc and
the current object curr . It then returns this new object.
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 12/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
Forum
The final value of acc will be the merged object, which will containDonate
all the properties ofto
Learn the original
code — freeobjects.
3,000-hour curriculum
const shoppingCart = [
{name: 'Apple', price: 1.99, quantity: 3},
{name: 'Apple', price: 1.99, quantity: 3},
{name: 'Xiomi', price: 2.99, quantity: 2},
{name: 'Samsung', price: 3.99, quantity: 1},
{name: 'Tesla', price: 3.99, quantity: 1},
{name: 'Tesla', price: 4.99, quantity: 4},
{name: 'Nokia', price: 4.99, quantity: 4},
]
return productGroup;
}, {});
console.log(products);
// OUTPUT
{
Apple: [
{ name: 'Apple', price: 1.99, quantity: 3 },
{ name: 'Apple', price: 1.99, quantity: 3 }
],
Xiomi: [ { name: 'Xiomi', price: 2.99, quantity: 2 } ],
Samsung: [ { name: 'Samsung', price: 3.99, quantity: 1 } ],
Tesla: [
{ name: 'Tesla', price: 3.99, quantity: 1 },
{ name: 'Tesla', price: 4.99, quantity: 4 }
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 13/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
],
Forum
Nokia: [ { name: 'Nokia', price: 4.99, quantity: 4 } ]
Donate
}
Learn to code — free 3,000-hour curriculum
The function first gets the name of the current product using
product.name . It then checks if there is already a group for this
product name in the productGroup object using the if statement.
If there is not, it creates a new group by initializing the
productGroup[name] property to an empty array.
Finally, the function pushes the current product into the group using
the push() method, and returns the updated productGroup object.
After the reduce() method has processed all the elements in the
shoppingCart array, the resulting productGroup object will contain
keys for each product name, and values that are arrays of products
with that name.
First, higher order functions can help improve the legibility of your
code by making it more concise and easy to understand. This can
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 14/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
Second, higher order functions can help organize your code into
smaller chunks, making it easier to maintain and extend.
Conclusion
This article explored what a higher order function is, the benefits of
using them, and how to use them in practical applications.
Now, whenever you try to use map(), filter() and reduce() methods
and get confused, just remember the following:
Sobit Prasad
Hey! I am Sobit a Frontend Developer from India. I love sharing what I have
learned through writing blogs on various platforms and threads on twitter.
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 15/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
If you read this far, thank the author to show them you care.
Forum Donate
Say Thanks
Learn to code — free 3,000-hour curriculum
Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers,
services, and staff.
Trending Guides
Mobile App
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 16/17
01/04/2024, 04:04 Higher Order Functions in JavaScript – Explained with Practical Examples
Forum Donate
Our Charity
About Alumni Network Open Source Shop Support Sponsors Academic Honesty
https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/ 17/17