Use Self-Executing JavaScript Functions for Code Isolation

When you first start learning JavaScript, you focus on getting down the basics. Then, after you work with JavaScript for a while, you learn more about variable scoping and the importance of isolating and protecting your code from outside influences.

What is variable scoping?

Variable scope refers to the context within which a variable is defined. Essentially, there are two contexts:

  1. Local Scope — JavaScript uses function-level scoping, so any variable that is defined within a function is considered a local variable.
function getPi() {
    var pi = 3.14159265359; // Local variable
    return pi;
}
  1. Global Scope — If a variable is defined outside of the context of a function, it is considered global.
var pi = 3.14159265359; // Global variable

function getPi() {
    return $pi;
}

Isolating Your Code by Controlling the Scope

As a best practice, you want to avoid setting variables in the global scope to prevent naming conflicts, overwritten variables, and improper access. Again, JavaScript uses function-level scoping, so if you want to avoid the global scope, you need only wrap your code in a function.

The best way to do this is to use an anonymous self-executing function immediately invoked function expression, which looks like this:

(function() {
    // Code goes here
})();

Essentially, the code in the function above will run as soon as it is loaded. Note the parentheses at the end; those are what cause the function to be run automatically.

If you want to pass in parameters, you can do so like this:

(function(win, doc, $) {
    // Code goes here
})(window, document, jQuery);

This approach allows you to alias the variables that are passed in from the global scope and makes minifying the code more effective.

Inserting all of your code into an immediately invoked function expression will effectively isolate it from the global scope and make sure that your code won’t be influenced by other code.