Passing a function as a parameter in JavaScript
In JavaScript, functions are first-class citizens, meaning they can be passed as arguments to other functions just like variables.
- This enables dynamic and reusable code.
- Allows higher-order functions, where one function controls or modifies another.
- Commonly used in callbacks, event handling, and asynchronous operations.
The below examples describe passing a function as a parameter to another function.
function geeks_inner(value){
return 'hello User!';
}
function geeks_outer(func){
console.log(geeks_inner());
}
geeks_outer(geeks_inner);
Output
hello User!
Example 2: This example passes a function geeks_inner along with an argument 'Geeks!' to the function geeks_outer as an argument.
function geeks_inner(value) {
return 'hello ' + value;
}
function geeks_outer(a, func) {
console.log(func(a));
}
geeks_outer('Geeks!', geeks_inner);
Output
hello Geeks!
Example 3: Here in this example, a smaller function is passed as an argument in the sayHello function. So here we are passing a smaller function address to the function sayHello.
function sayHello(param) {
console.log("hello", param);
param();
return "Hiii Geeks for Geeks"
}
// Function address
function smaller() {
console.log("Is everything alright")
}
// Function call
const returnHello = sayHello(smaller)
console.log(returnHello)
Output
hello [Function: smaller] Is everything alright Hiii Geeks for Geeks