In JavaScript, functions are first-class objects, which means they can be stored in variables, passed as arguments, and returned from other functions.
- A function can be passed to another function as an argument.
- The receiving function can execute the passed function when needed.
- This makes code more reusable and flexible.
- This concept is commonly used with callbacks, event handlers, and higher-order functions.
The following approaches demonstrate how to pass a function as a parameter in JavaScript.
Approach 1: Passing a Function Without Arguments
A function can be passed directly as an argument to another function. The receiving function can then call it using ().
function geeksInner() {
return "Hello User!";
}
function geeksOuter(func) {
console.log(func());
}
geeksOuter(geeksInner);
Output
Hello User!
- geeksInner is passed to geeksOuter without parentheses.
- func receives the function reference.
- func() executes the passed function.
Note: Use geeksInner when passing the function. Using geeksInner() would execute the function immediately and pass its returned value instead.
Approach 2: Passing a Function with Arguments
A function can also be passed along with additional arguments. The receiving function can pass those arguments to the callback when it executes it.
function geeksInner(value) {
return "Hello " + value;
}
function geeksOuter(value, func) {
console.log(func(value));
}
geeksOuter("Geeks!", geeksInner);
Output
Hello Geeks!
- geeksInner accepts the value passed to it.
- geeksOuter receives both the value and function reference.
- func(value) executes the passed function with the provided argument.
Approach 3: Passing an Anonymous Function
An anonymous function can be created directly while calling another function and passed as an argument.
function sayHello(func) {
console.log("Hello User!");
func();
}
sayHello(function () {
console.log("Welcome to GeeksforGeeks!");
});
Output
Hello User! Welcome to GeeksforGeeks!
- The anonymous function is passed directly to sayHello().
- func stores the function reference.
- func() executes the anonymous function.
Approach 4: Using an Arrow Function
An arrow function can also be passed as a parameter, providing a shorter syntax for callbacks.
function calculate(a, b, operation) {
return operation(a, b);
}
const result = calculate(10, 5, (x, y) => x + y);
console.log(result);
Output
15
- calculate() receives two numbers and a function.
- The arrow function (x, y) => x + y is passed as the third argument.
- operation(a, b) executes the passed function.