Passing Javascript Functions to Other Javascript Functions as Arguments

In my last post, I briefly talked about variables, functions and how you can put functions into variables to be later called using the variable name.

In this mini post, I will talk about passing Javascript functions to other Javascript functions as arguments (parameters).

functions as variables

As I said in my previous post “Functions as Variables in Javascript“, once we assign a Javascript function to a variable, it is possible to use this function as an argument (parameter) for other Javascript functions.

Now let’s go through the sample above and explain what it does, how it works.

In the first part (the first 3 lines) we create a variable (speak) and assign a function to it which accepts another Javascript function as a parameter (paramFunction) and calls/invokes this function in its body.

In the second part (next 3 lines) we create another variable (Hi) and assign a function to it. This function¬†alerts a¬†“Hi” message appending whatever is provided as an argument to it.

In the last line, we call “speak” function providing “Hi” function as a parameter which ends up alerting “Hi. I can speak.” message.

As you can see, once you put a function inside a Javascript variable it is quite straight forward to provide this function as an argument to another Javascript function.

Hope this helps.
Good Luck,

Leave a Reply

Your email address will not be published. Required fields are marked *