Self-invoking functions in Javascript

Samah Gaber
3 min readOct 18, 2020

IIFE — IMMEDIATELY INVOKED FUNCTION EXPRESSION

Photo by Roman Synkevych on Unsplash

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 explain what a self invoking function is and why you should consider them.

In JavaScript, functions are usually declared like this:

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

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 like this:

myFunctionName ("Function parameters");

A self-invoking function is a nameless (anonymous) function that is invoked immediately after its definition.

An anonymous function is enclosed inside a set of parentheses followed by another set of parentheses (), which does the execution.

(function(){
console.log("This function is called immediately");
})();

Self-invoking functions are useful for initialization tasks. For example, if we have a web page in which we want to attach event listeners to DOM elements and other initialization work, self-invoking functions would be the best tool for the job!

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.

How they actually work ?

Since the function is defined anonymously, there are neither global nor even local variables except, of course, the variables declared inside the function’s body. We do not keep reference to the function, not even to its return value. After the function has been initialized, it is being immediately invoked and it’s executed only once as after the execution we’ll lose the reference to the function.

How to write them ?

There is a few small (but important) syntax variations. Douglas Crockford’s JSLint offers the correct declaration for self-invoking functions as:

(function () {
// body
}());

An alternative syntax, which Crockford calls “dog balls”, is as follows:

(function () {
// body
})();

I personally find the second variant to be more clear.

You can also pass parameters to the self-invoking functions. It is a commonly used practice to pass references to global objects:

(function (w, d, $) {
// body
}(window, document, jQuery));

A self-invoking function can have variables and methods but they cannot be accessed from outside of it. To access them, the global window object has to be passed as a parameter.

Consider a self-invoking function below, containing the variable pi and the function e(). A global window object is passed and both pi and e() are assigned to the global variables window.pi and window.e respectively

(function(window){
var pi = 3.141;
function e() {
return Math.E;
}

window.pi = pi;
window.e = e;
})(window);

In the browser console, the command pi will return 3.141 and the command e() will return 2.718281828459045.

> pi; // 3.141
> e(); // 2.718281828459045

Important note:

In programming we usually call functions which invoke themselves recursive functions. That is the reason Ben Alman gave self-invoking functions a new name: Immediately Invoked Function Expression (IIFE). It is recommended to use the term IIFE since it’s semantically correct and more clear.

Conclusion

The purpose of wrapping the function is for the namespace and controling the visibility of member functions. It wraps the code inside a function scope and decreases clashing with other libraries. And it’s useful for initialization tasks.

Thank you for your time. Any comments and feedback are most welcomed 😊

--

--