JavaScript 101: The Module Pattern

The Module is one of the most well known JavaScript coding patterns, and one which fully takes advantage of JavaScript’s scope closures.

Let’s look at a basic JavaScript module implementation.

function MyModule {
  var first = "one";
  var others = [2, 3];

  function doFirst() {
    console.log(first);
  }

  function doOthers() {
    console.log(others.join(","));
  }

  return {
    doFirst: doFirst,
    doOthers: doOthers,
  }
}

var foo = MyModule();

foo.doFirst(); // one
foo.doOthers(); // 2,3

Our module, MyModule, is nothing but a simple JavaScript function. In order for a module instance (foo) to be created, we need to invoke MyModule(). It returns an object containing references to its inner functions doFirst and doOthers, but its inner variables are kept private.

It’s common to say that the returned object is a public API for our module. We are then able to call the API methods on our module instance, when we call foo.doFirst() or foo.doOthers().

The module pattern thus follows a couple of rules:

  • There is an outer function (MyModule()) and it’s invoked at least once, or every time a new module instance it’s created.
  • This outer function returns at least one inner function (foo.doFirst() and foo.doOthers()), which has closure over the private scope, and can access and/or modify the private state.

MyModule can be invoked any number of times, to create any number of MyModule instances. A variation on this is when we’re defining a singleton module, one which can only have one instance.

var foo = (function MyModule {
  var first = "one";
  var others = [2, 3];

  function doFirst() {
    console.log(first);
  }

  function doOthers() {
    console.log(others.join(","));
  }

  return {
    doFirst: doFirst,
    doOthers: doOthers,
  }
})();

foo.doFirst(); // one
foo.doOthers(); // 2,3

All we did was turn MyModule into an IIFE, and assigned it to our single module instance, foo.

Simple, huh? Happy coding everyone!