If you’re starting out with JavaScript, you might have heard the term higher-order function and wondered what it means. It sounds complicated, but I promise it’s not! By the end of this post, you’ll understand what higher-order functions are, see some examples, and learn why they are so useful.
What Is a Higher-Order Function?
In JavaScript, functions are first-class citizens. This means:
- You can store functions in variables.
- You can pass functions as arguments to other functions.
- You can return functions from other functions.
A higher-order function is any function that does one or both of the following:
- Takes one or more functions as arguments.
- Returns a function.
That’s it! No tricky concepts — just functions that deal with other functions.
A Simple Example: Passing a Function as an Argument
Let’s see a higher-order function in action.
function greet(name) {
console.log(`Hello, ${name}!`);
}
function processUserInput(callback) {
const name = prompt("Please enter your name:");
callback(name);
}
processUserInput(greet);
In this example:
-
processUserInput
is a higher-order function because it accepts another function (greet
) as an argument. -
greet
is called insideprocessUserInput
to display the greeting.
Example: Returning a Function
A higher-order function can also return a new function. Here’s how:
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // Output: 10
What’s happening here?
-
multiplier
is a higher-order function because it returns another function. - We create
double
by callingmultiplier(2)
, which gives us a function that doubles numbers.
Why Use Higher-Order Functions?
Higher-order functions help make your code:
- Reusable — You can apply the same logic in different situations by passing different functions.
- Cleaner and shorter — No need to repeat similar logic in multiple places.
- Flexible — Combine small, focused functions to create powerful features.
In fact, many of JavaScript’s built-in array methods are higher-order functions!
Built-In Higher-Order Functions in JavaScript
Let’s look at some examples you might already be familiar with.
const numbers = [1, 2, 3, 4, 5];
// map applies a function to each element
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter keeps elements that match a condition
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
// reduce combines all elements into one value
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15
map
, filter
, and reduce
all take functions as arguments — that’s what makes them higher-order!
Final Thoughts
Higher-order functions are functions that work with other functions.
They might sound intimidating at first, but they’re everywhere in JavaScript. Once you understand them, you’ll be able to write smarter, cleaner, and more reusable code.
Top comments (0)