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 w3wiki.
Javascript
function greet(name) { return `Hi!! ${name} `; } function greet_name(greeting, message, name) { console.log(`${greeting(name)} ${message}`); } greet_name(greet, 'Welcome To w3wiki' , 'Geeks' ); |
Hi!! Geeks Welcome To w3wiki
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);