Control the Scope of JavaScript Declarations with IIFEs

One of the most common mistakes people make with JavaScript is polluting the global namespace with too many low-level function and variable declarations and then running into subtle bugs when one declaration stomps on another.

For example, if you declare something like var foo = "value"; in a JavaScript file that gets pulled into your HTML page through a script tag, that foo variable is now in the global namespace. You could have some other JavaScript file that also gets pulled in that also declares a foo variable, puts a different value in it, and then your code could start doing unintended things because of the value supplied by that other JavaScript file. If your foo variable is only intended to be used by other code in the same JavaScript file, there's a simple and common structure to be aware of for controlling that scope: Immediately Invoked Function Expressions (IIFEs), also sometimes referred to as automatically invoked functions, or self-invoking functions.

All you need to do is wrap the contents of your JavaScript file in the following syntax:

(function()  
// Your code  here 
})(); 

Now, any variables you declare inside that function are local variables that won't pollute the global namespace and can't be stomped on by other JavaScript files being executed in the same page or scope. Those variables can still be used by any functions declared within that "Your code here" scope through the magic of closures, so you have a nice atomic, modular approach to declaring your chunks of functionality. You'll see this as a common approach to declaring things such as modules, controllers, directives and services in Angular code, for example.

Posted by Brian Noyes on 02/23/2015


Keep Up-to-Date with Visual Studio Live!

Email address*Country*