Approach 2 Functions as Return Values
Higher-order functions can also return new functions. This is often used for creating specialized functions or closures. For instance, you can create a function factory that generates functions with specific behavior.
Example: In this example, `multiplier` is a higher-order function that takes a `factor` as an argument and returns a new function that multiplies any number by that factor. We then use `double` and `triple` to create specialized functions.
Javascript
function multiplier(factor) { return function (x) { return x * factor; }; } const double = multiplier(2); const triple = multiplier(3); console.log(double(5)); console.log(triple(5)); |
Output
10 15
JavaScript Higher Order Functions
In JavaScript, a higher-order function is a function that can accept other functions as arguments, return functions, or both. They enable abstraction, composition, and the creation of more flexible and reusable code.
Syntax:
function higherOrderFunction(callback) {
// Perform some operations
// Call the callback function
callback();
}
function callbackFunction() {
console.log("Callback function is executed.");
}
// Passing the callback function to the higher-order function
higherOrderFunction(callbackFunction);