The JavaScript Module Pattern, how and why?

Published by in January, 2017

Categorized in: Dev Stuff

Tags: JavaScript  

The Module Pattern in JavaScript was created by software engineers in 2003. The purpose of the module pattern is to emulate objects with private and public methods in a closure that shields internal methods from the global scope and namespace protection from other scripts. The structure of the module pattern is emulates an object literal if you are familiar with that.

Here's a simple module to log a message:.


var yourModule = (function() {
    var privateVariable;
    var anotherPrivateVariable = "Hey man!";
    var aPrivateFunction = function() {
        console.log(anotherPrivateVariable);
    }
    
    return {
        logTheVariable: function() {
           aPrivateFunction();
        }
    };
})();

//usage
yourModule.logTheVariable(); //returns "Hey man!"

Notice the object module contains an immediately invoked function. Here the privateVariable, anotherPrivateVariable and aPrivateFunction are completely shielded from the global scope. Only our returned function logTheVariable can access the scope of the private variables and methods. Finally we've namespaced our module with the object yourModule.

Now you should be on your way to writing cleaner application code. In another post I'll discuss another variation of the Module Pattern called the Revealing Module Pattern.

References:

  1. https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript
  2. http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html