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);

Similar Reads

Parameters:

higherOrderFunction: Takes a callback function, executes it, and performs operations. callback: A function passed as an argument, executed inside higherOrderFunction. callbackFunction(): Logs “Callback function is executed.” Invocation: Calls higherOrderFunction(callbackFunction), executing callbackFunction within higherOrderFunction....

Approach 1: Function as an Argument:

This approach involves passing a function (callback) as an argument to another function. The receiving function can then execute the callback, enabling flexible and customizable behavior in JavaScript programs....

Approach 2 : Functions as Return Values:

...

Contact Us