Higher-order functions are functions that can take other functions as arguments or return functions as their results. This concept enables powerful and flexible programming techniques in JavaScript. Here's an explanation and example:
In JavaScript, functions are considered first-class citizens, which means they can be treated like any other value, such as strings or numbers. This allows us to pass functions as arguments to other functions or even return functions from functions.
Let's consider an example where we have a higher-order function called calculator
that takes two numbers and a callback function as arguments. The calculator
function performs a calculation on the two numbers and passes the result to the callback function.
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function calculator(num1, num2, callback) {
return callback(num1, num2);
}
console.log(calculator(5, 3, add)); // Output: 8
console.log(calculator(5, 3, subtract)); // Output: 2
In this example, we define two simple arithmetic functions add
and subtract
. The calculator
function takes two numbers and a callback function as arguments. It calls the callback function with the given numbers and returns the result.
When we call calculator(5, 3, add)
, the add
function is passed as the callback. The calculator
function executes the add
function with the arguments 5
and 3
, which returns the sum of the two numbers (8
).
Similarly, when we call calculator(5, 3, subtract)
, the subtract
function is passed as the callback. The calculator
function executes the subtract
function with the arguments 5
and 3
, which returns the difference between the two numbers (2
).
This example demonstrates how higher-order functions can be used to encapsulate reusable logic and make code more modular. It allows us to pass behavior (functions) as arguments, providing flexibility and enabling code to be more expressive and adaptable.
Top comments (0)