Why it is a good idea to wrap the entire content of a JavaScript source file in a function block?

This technique creates a closure around the entire contents of the file which creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries. Closure is a mechanism to declare "private" variables in JavaScript. You can learn more about closures here.

/* Variables placed outside of self-executed function will be considered as global */

var globalVar = 'bar';

(function() {
  /* Variables placed inside of this function will be considered private */

  /* You won't see privateVar in global scope */
  var privateVar = 'foo';
})();

This is an increasingly common practice, employed by many popular JavaScript libraries (jQuery, Node.js, etc.).

Another feature of this technique is to allow for an easily referenceable (presumably shorter) alias for a global variable. This is often used, for example, in jQuery plugins. jQuery allows you to disable the $ reference to the jQuery namespace, using jQuery.noConflict(). If this has been done, your code can still use $ employing this closure technique, as follows:

(function($) {
    /* jQuery plugin code referencing $ */ 
})(jQuery);

Short answer

  • Closure is a mechanism to declare "private" variables in JS.
  • By wrapping all code in JS file you create closure, hence create private namespace, which helps avoid potential name clashes between different JavaScript modules and libraries.
  • Also, it allows to use easily referenceable (presumably shorter) alias for a global variables.

Similar articles

Comments