in Js

Immediately-Invoked Function Expression (IIFE)


Immediately-invoked function expression, in short IIFE is a JavaScript pattern which is often used when trying to avoid polluting the global namespace. All variables that are used inside IIEF cannot be accessed outside its scope.

Getting Started

IIFE executes immediately after it’s created. The main advantage of using this pattern is avoiding the global namespace pollution. Now what exactly is global namespace pollution ?

As many claims using too much global namespace is bad. Why ? If we are using libraries or in a large projects, we may have shared the same global object or in a simpler way, we may have declared a global variable with the same name. This will bring up collision between those variables or functions, who knows what are executing and what are not. Using too much global namespace is referred as global namespace pollution.

Let’s see a simple demonstration :

we have two js files, one of them index.js and another one sachin.js.

Now we’ll have both files with a variable named me but with different values.

If we open up the index.html file, we’ll have both ‘Index’ and ‘sachin’ String in our console. This is alright for now but what if we invoke ‘me’ in console or in our index.html. This will return ‘sachin’ . Can you guess it why ?

when our document html loads, it will load index.js and after that sachin.js and the global variable me will be overridden by our sachin.js so it will print out sachin.

It’s just a simple demonstration, but let’s think what might happen if we have no. of files . This is where IIEF comes in.

We can cover up the whole code with bracket making them invokable and function call. Using this way, if we again call me, it will return index. This is how we can avoid global namespace pollution.

Happy coding 🙂