What is a Self Invoking Function

Sharing is Caring

In JavaScript, it’s common to hear lots of strange terminology without a lot of description around what it is or what it does. I want to try and demystify what a self invoking function is and why you should consider them and the times when maybe you shouldn’t consider them.

In JavaScript, functions are usually declared like this:

function myFunctionName (someAwesomeParameters) {
//some code that does something awesome.
}

This is called a declared function. Declared functions are not executed immediately. Basically, declared functions are saved for you to use them somewhere else so this means it’s not called upon or “invoked” until you call it.

Calling the function would look something like this:

myFunctionName ('Brian is Awesome');

A self invoked function is a function that can call itself because it’s anonymous and executes automatically.

(function() {

// some code here

})();

As you may notice, the self invoked function is made up of two parts the anonymous part:

(function() {

// some code here

})

And then the call to execute which is simply the closing braces

();

As soon as the function has been defined, it will immediately be called or invoked. I really like to use self invoking functions for doing initialization of things or adding event listeners or changing the layout of a page. In jQuery, usually a self invoked function was used instead of setting documment.ready

The primary benefit of self-invoking functions is that they execute only once and won’t fill the global namespace with all sorts of crud that lasts for the lifetime of the page.

It doesn’t seem like adding a few things to the global namespace would be a problm until you start getting into thousands of lines of javascript and having collisions between functions or variables.

Self invoking functions are commonly used for artificially creating namespaces which don’t natively exist in JavaScript.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.