Design Patterns in JS: The Module Pattern

June 02, 2018

Building Blocks

The Module Pattern is one of the most commonly used design patterns in Javascript. The module pattern exists to create privacy and separation in your code- keeping variables and functions out of the global scope.

The module pattern presents as an Immediately-Invoked Function Expression (IIFE). All that an IIFE does is create a function which is called immediately. Here’s an example:

(function() {
    // Oh look, I'm hanging out inside a module
    // How wonderful
}());

Or, with an ES6 arrow function,

(() => {
 // All of the mapping, reducing and filtering. ES6 FTW.
})();

All of the variables and functions declared within the IIFE are kept out of the global scope.

The module can also be namespaced in order to lay the groundwork for returning publicly accessible methods and properties:

const myModule = (() => {
 return {
   publicMethod: function () {
     console.log('hello.');
     }
   }
})();

myModule.publicMethod();
// hello.

A close relative to the Module Pattern is something called the Revealing Module Pattern. This is a module that returns certain properties or methods in an easy-to-read syntax, thus revealing part of itself for public use:

const myModule = (() => {

 const privateMethod = function () {
   console.log(`shhhh, it's a secret`);
   };

 const privateVariable = 'foo';

 const publicMethod = function () {
   console.log('hello');
 };

 const publicVariable = 'bar';

 return {
   publicMethod: publicMethod,
   publicVariable: publicVariable
 };

})();

This makes only the defined methods and variables accessible outside the module, and is easy to read since the return object is generally put at the bottom of the module.


John D Potts

John D Potts

Web developer and speaker in Charlotte, NC.