Avoid polluting global namespace in Javascript- IIFE (Immediately Invoked Function Expression)

tn500w_javascript-logo

Avoid polluting global namespace in Javascript- IIFE (Immediately Invoked Function Expression)

Everybody says Global variables are bad, they are evil, it produces abnormal behavior. In the browser environment everything you load is in a single space. An HTML page may be linked to 1, 2, or 10 JS files. Each JS file may contain code that is written by completely different person. All those scripts execute in a single space in that page. This is the problem. So, if you use global variables, then its available for all the JS files linked to that HTML file. And it can be easily modified if used(unknowingly), can cause unexpected result. You can clash with a global variable that some other JS file uses. Avoid global variables, with global variables we pollute the global namespace.

var a=10;
var b=10;
console.log(a+b);

For the above code, a & b are global variables, it may happen that suppose if we are using JS libraries & if those JS libraries are using a & b vaiables then you are polluting them. Let’s prevent these from becoming global. Let’s use function scoping and wrap the above code around a function.

function myFn(){
   var a=10;
   var b=10;
   console.log(a+b);
}
fn();

Oh yeah! problem solved, now a & b variable are accessible inside myFn function only. But wait a minute, a new problem arises, you have removed 2 global variables but you created a new global function(with name myFn). So, if somebody in his JS files uses myFn() then code gets polluted. We know that functions are objects in Javasript, so it may happen the myFn which was pointing to a function object is now pointing to our function now. Weird!.

In order to avoid this what we do is, use a structure which is kind of funny. We stated a problem above due to function scoping, which arises due to function name. So it seems that we have to provide function scoping but without function name(kind of anonymous). But if function will not have a name, then how we gonna execute that function. IIFE structure to the rescue. IIFE stands for Immediately Invoked Function Expression. This structure executes the function as soon as it gets declared.

(function(){
   var a=10;
   var b=10;
   console.log(a+b);
})();

As you can see above, there’s no name to the above function, and the function also gets executed as soon as it’s declared. This is a common structure that is used to execute anonymous functions directly. What we did id that instead of wraping aroud a function and giving it a name, and then execute it separately, we just execute it inline with an anonymous function. Now a & b cannot be accessed globally, and also since the function does not have a name, so we are not polluting the global namespace with the function name. we can also term it as anonymous function scoping.

About Anoop Kumar Rai