Modules in Javascript


Reasons for Modules

Using Modules - Three Approaches

Module Pattern


Reasons for Modules

  • maintainability
  • namespacing
  • reusability

Using Modules - Three Approaches

Module Pattern

Anonymous Closure

  (function () {
    // ... all vars and functions are in this scope only
    // still maintains access to all globals

An anonymous closure has its own evaluation environment -- the scope of the anonymous function protects variables inside the closure. You can use variables inside the closure without fear of overwriting global variables, but you still have access to any global variables.

Note that the "()" around the anonymous function is required, because any statement that begins with function is always considered to be a function declaration.

See the Pen d21b316c6b5b95bc12d64fada9b1a2e6 by Chris D'Iorio (@cediorio) on CodePen.

Global Import

  (function ($, YAHOO) {
      // now have access to globals jQuery (as $) and YAHOO in this code
  }(jQuery, YAHOO));

A global import both makes the import/use of globals in the closure explicit and also makes the code run faster (presumably because the interpreter does not have to climb back up the chain to find the global variable).

See the Pen Global Import by Chris D'Iorio (@cediorio) on CodePen.

Object Interface or Module Export

  var MODULE = (function () {
    var   myVar             = {},         
          privateVariable   = 1;

    function privateMethod() {
      // ...

    my.moduleProperty = 1;
    my.moduleMethod = function () {
      // ...

    return myVar;

With this module pattern, you actually declare a global module with public properties. The example above has a public property "moduleProperty" and a public method "moduleMethod". It also has a "privateVariable" and a "privateMethod" that have private internal state because of the closure provided by the anonymous function. Note that you could also pass in a global variable using the "Global Import" method noted above.

See the Pen Object Interface by Chris D'Iorio (@cediorio) on CodePen.

Revealing Module

    var revealingModule = (function(){
      var privateVar  =   "private variable",
          publicVar   =   "public variable";
      function privateFunction(){
        return privateVar;
      function setVar(e) {
        privateVar = e;
      function getVar(){
      // reveal public pointers to private functions and properties
      return {
        setVar: publicSetVar,
        value: publicVar,
        getVar: publicGetVar

The Revealing Module pattern creates public pointers to private functions.

See the Pen Revealing Module by Chris D'Iorio (@cediorio) on CodePen.