JavaScript Higher Order Functions
Last Updated :
03 Nov, 2023
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);
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.
We will explore all the above methods along with their basic implementation with the help of examples.
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.
Example: In this example, Two functions: greet accepts name and returns a greeting. greet_name combines greeting, message, and name, logging a customized message. Output: “Hi!! JavaScript Welcome To GeeksForGeeks.
Javascript
function greet(name) {
return `Hi!! ${name} `;
}
function greet_name(greeting, message, name) {
console.log(`${greeting(name)} ${message}`);
}
greet_name(greet, 'Welcome To GeeksForGeeks' , 'Geeks' );
|
Output
Hi!! Geeks Welcome To GeeksForGeeks
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));
|
Share your thoughts in the comments
Please Login to comment...