Functions as Variables in Javascript

A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when “something” invokes it (calls it). A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). (w3schools)

In this mini post, I will briefly mention the concept of functions as variables in Javascript. Learn it. It will help a lot.

Consider the example below:

I think everybody even with just the smallest amount of javascript experience is familiar with the notation above. Here “sayhi” is the name of our javascript function.

Now let’s see how we can change the above syntax, assign some javascript snippet to a javascript variable and call the function (execute the snippet) using that variable’s name.

As you can see, here I have used a variable to put some javascript code into it and I called/executed the javascript code using that variable’s name.

And you know what… Now we can pass this function to other javascript functions just like any other variable! Cool huh?

Hope this helps.
Good Luck,

Leave a Reply

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