Higher-Order Functions in JavaScript
Abdul Ahad Abeer
Posted on September 27, 2024
A higher-order function is a function that either takes one or more functions as arguments or Returns a function as its result. These functions are a key concept in functional programming and allow for more abstract, reusable, and modular code.
Example of a Higher-Order Function
Function that takes another function as an argument:
function greet(name) {
return `Hello, ${name}`;
}
function logGreeting(fn, name) {
console.log(fn(name));
}
logGreeting(greet, 'John'); // Hello, John
n this example, logGreeting
is a higher-order function because it accepts another function (greet
) as an argument.
Function that returns another function:
function multiplyBy(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplyBy(2);
console.log(double(5)); // 10
Here, multiplyBy
is a higher-order function because it returns a new function that multiplies a number by the specified factor
.
We can see there are some built-in Higher-Order Functions in JavaScript. Some of them are:
map()
filter()
reduce()
forEach()
every()
Posted on September 27, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 24, 2024