Higher-order functions in JavaScript are functions that accept other functions as arguments, return functions as results, or do both. They help developers write reusable, flexible, and organized code.
Higher-order functions are commonly used in array methods such as map(), filter(), and reduce(), as well as in event handling and asynchronous programming.
In this tutorial, you will learn what higher-order functions are, how they work, and how to use them with practical JavaScript examples.
What Are Higher-Order Functions in JavaScript?
A higher-order function is a function that takes another function as an argument or returns a function.
For example, a function that accepts a callback function is a higher-order function.
function greet(name) {
console.log("Hello, " + name);
}
function processUser(callback) {
callback("Karim");
}
processUser(greet);
Output:
Hello, Karim
In this example, processUser() accepts greet as an argument and calls it. Therefore, processUser() is a higher-order function, while greet() is the callback function.
Learn more about JavaScript Callback Functions to understand how functions can be passed to other functions.
Higher-Order Functions That Accept Functions
A higher-order function can accept another function as a parameter and execute it when needed.
Example of a Higher-Order Function
function calculate(a, b, operation) {
return operation(a, b);
}
function add(x, y) {
return x + y;
}
console.log(calculate(10, 20, add));
Output:
30
Here, calculate() receives two numbers and a function called operation. It calls that function with the supplied numbers and returns the result.
You can pass different operations without rewriting the calculate() function.
function calculate(a, b, operation) {
return operation(a, b);
}
console.log(calculate(10, 5, (x, y) => x + y));
console.log(calculate(10, 5, (x, y) => x - y));
console.log(calculate(10, 5, (x, y) => x * y));
Output:
15
5
50
This example demonstrates how higher-order functions make code more flexible.
Higher-Order Functions That Return Functions
A function can also return another function. In this case, the outer function is a higher-order function.
Example of Returning a Function
function greetUser() {
return function() {
console.log("Welcome to Web4Learners!");
};
}
const greet = greetUser();
greet();
Output:
Welcome to Web4Learners!
The greetUser() function returns an inner function. The returned function is stored in greet and executed when greet() is called.
This pattern is also related to closures, where an inner function can retain access to variables from its enclosing scope.
Higher-Order Functions with map()
The map() method is a built-in higher-order function for arrays. It calls a callback function for each element and creates a new array containing the returned results.
Example of map()
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(number) {
return number * 2;
});
console.log(doubled);
Output:
[2, 4, 6, 8, 10]
The callback multiplies each number by two. The map() method returns a new array without changing the original array.
Higher-Order Functions with filter()
The filter() method creates a new array containing only the elements that pass a specified condition.
Example of filter()
const numbers = [10, 15, 20, 25, 30];
const result = numbers.filter(function(number) {
return number >= 20;
});
console.log(result);
Output:
[20, 25, 30]
The callback returns true for numbers greater than or equal to 20. Those elements are included in the new array.
Higher-Order Functions with reduce()
The reduce() method processes array elements to produce a single accumulated result.
Example of reduce()
const numbers = [10, 20, 30, 40];
const total = numbers.reduce(function(sum, number) {
return sum + number;
}, 0);
console.log(total);
Output:
100
The callback adds each number to the accumulated value. The initial accumulator value is 0, and the final result is 100.
Benefits of Higher-Order Functions
Higher-order functions offer several advantages:
- Code reuse: Use the same function with different callback functions.
- Flexibility: Change how a function behaves by passing different functions.
- Readability: Array methods such as
map()andfilter()clearly express common operations. - Less repetition: Perform common data-processing tasks without repeatedly writing loops.
- Functional programming: Support patterns that treat functions as values and encourage reusable operations.
Frequently Asked Questions
What is a higher-order function in JavaScript?
A higher-order function is a function that accepts another function as an argument, returns a function, or does both.
Is map() a higher-order function?
Yes. The map() method accepts a callback function and applies it to array elements to create a new array.
What is the difference between a callback and a higher-order function?
A callback is a function passed to another function. A higher-order function is the function that accepts a function as an argument or returns a function.
Can a higher-order function return another function?
Yes. A function that returns another function is a higher-order function.
Are higher-order functions used in asynchronous JavaScript?
Yes. They are used in event handlers, timer callbacks, and many asynchronous programming patterns.
Why are higher-order functions useful?
They improve code reuse, flexibility, and readability. They are especially useful when processing arrays or creating functions that can perform different operations based on supplied callbacks.
3 thoughts on “JavaScript Higher-Order Functions”
Comments are closed.