Passing a function as a parameter in JavaScript

In this article, we will pass a function as a parameter in JavaScript. Passing a function as an argument to the function is quite similar to passing a variable as an argument to the function. So variables can be returned from a function.
The below examples describe passing a function as a parameter to another function.
Example 1: This example passes a function zambiatek_inner to the function zambiatek_outer as an argument.
Javascript
function zambiatek_inner(value){ return 'hello User!';}function zambiatek_outer(func){ console.log(zambiatek_inner());}zambiatek_outer(zambiatek_inner); |
hello User!
Example 2: This example passes a function zambiatek_inner along with an argument ‘Geeks!’ to the function zambiatek_outer as an argument.
Javascript
function zambiatek_inner(value) { return 'hello ' + value;}function zambiatek_outer(a, func) { console.log(func(a));}zambiatek_outer('Geeks!', zambiatek_inner); |
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.
Javascript
function sayHello(param) { console.log("hello", param); param(); return "Hiii Geeks for Geeks"}// Function addressfunction smaller() { console.log("Is everything alright")}// Function callconst returnHello = sayHello(smaller)console.log(returnHello) |
hello [Function: smaller] Is everything alright Hiii Geeks for Geeks



