The Module Pattern is not a new topic or unique to JavaScript. Yet for many that are new to JavaScript, the Module Pattern is a topic that eludes. Whether you are an experienced JavaScript developer or are just getting acquainted with the language, knowing what the Module Pattern is and how to implement it, it is absolutely essential if you hope to attain success with JavaScript. In this article, I will briefly cover what the Module Pattern is and how you can immediately apply the pattern.

The Module Pattern makes your JavaScript more manageable, testable and maintainable. With the Module Pattern, you avoid the pitfalls with global variables. The Module Pattern helps to maintain compatibility among the various JavaScript libraries used in your project. If you decide to do one thing to write better JavaScript Code and you are not already employing the Module Pattern, make that one thing to employ the Module Pattern.

If you decide to do one thing to write better JavaScript Code and you are not already employing the Module Pattern, make that one thing to employ the Module Pattern.

What is the Module Pattern?

In general, the Module Pattern is a software coding pattern that organizes code into distinct code blocks, also referred to as modules. These modules expose properties and behaviors. If you are equating modules to classes, it is a partially correct analogy. Both modules and classes are mechanisms for organizing and encapsulating code, but there are key differences between them. Those differences are beyond this article's scope. What's important to keep in mind is that modules are a mechanism for organizing code. Functionally, the module pattern also aides in reducing, and thereby eliminating conflicts with public variables. In the JavaScript realm, the jQuery library is an example of the Module Pattern in action.

The following is the basic JavaScript module structure:

(function () {
    // variable declarations
    // function declarations
    // still have access to globals

}());

Closures are one of JavaScript's most powerful features. A closure provides a level of encapsulation to private variables and the functions it contains. In addition, closures also provide access to other variables that were in scope when the closure was declared. There are two important aspects to the code. First, the function is wrapped in parenthesis. Second, the function itself is appended with two parentheses. This makes the function self-executing. The next section illustrates the concept with a simple hello world example.

If you decide to do one thing to write better JavaScript Code and you are not already employing the Module Pattern, make that one thing to employ the Module Pattern.

A Hello World Module

Listing 1 illustrates a JavaScript Module with basic functionality.

This basic module contains two members: a private variable named _aPrivateVariable and a public function named myFunction. MyFunction returns the private variable _aPrivateVariable's value and also returns the public function setaPrivateVariable that changes the private variable's value. This module, when loaded, executes immediately. The result is a single global variable named myModule. Listing 1 is an example of exporting a module. This is also an example of the Singleton Pattern, meaning that there will only be one module instance and that such instance is accessed via the myModule global variable.

Listing 1: A basic JavaScript Module

var myModule = (function () {
    var _myModule = {};

    var _aPrivateVariable = "Hello World!";

    _myModule.myFunction = function () {
        return _aPrivateVariable;
    }

    _myModule.aPublicVariable = "A public Variable";
    _aPrivateVariable = value;

    return _myModule;
}());

The following code is an example of how to interact with the module illustrated in Listing 1:

myModule.aPublicVariable = "Cool";
alert(myModule.aPublicVariable);
alert(myModule.myFunction());
myModule.setaPrivateVariable("The New Value");
alert(myModule.myFunction());

There is nothing here that is all that useful. For something useful, let's create a RESTful API module.

A RESTful API Module

Chances are, if you are working with JavaScript, you are also working with a RESTful API and using jQuery to make your API calls. The Module Pattern is a great way to organize your API calls. Listing 2 illustrates a simple example that wraps a RESTful API in a JavaScript Module.

Listing 2: RESTful API Wrapper Module

var productsAPI = (function ($) {
    var _productsAPI = {};
    var _baseUrl = "http://localhost:42280/api/products/";

    _productsAPI.get = function (callback,id) {

        id = (id === undefined) ? "" : id;
        var _url = _baseUrl + id + "?callback=?";

        $.ajax(_url,
        {
            type: "GET",
            dataType: "json"
        })
        .done(function (data) {
            callback(data);
        });
    }
    return _productsAPI;
}(jQuery));

This example also illustrates how to import existing global variables into your module. In this case, the global variable jQuery is assumed to be in scope. The parameter name is the $ sign. This technique protects the code from variable conflicts. In this example, you can be assured that the $ alias refers to jQuery and nothing else. This module has one public method, named Get, that accepts up to two parameters. The first is the callback function that accepts the returned data and an ID. Note the checks to see if the ID is undefined. If an ID is not passed into the function, all products are returned. Otherwise, the product corresponding to the passed ID will be returned. The following is an example of how to interact with the API.

var callback = function (data) {
    //do something with the returned data.
}

productsAPI.get(callback,1);

In the current implementation, the API URL is fixed. In actual practice, you would want to make that configurable as follows:

_productsAPI.setUrl = function (url) {
    _baseUrl = url;
}

With a configurable URL, you can now set the URL to a local file and in the process, make your code unit testable.

Conclusion

Implementing the Module Pattern may be the single most important tip you will encounter with JavaScript. With the pattern, your JavaScript code becomes more maintainable, readable, reusable and testable. It is these four areas from which most complaints about JavaScript arise.

The Module Pattern is not a new concept and there are many examples that illustrate its use. Every jQuery plugin follows this pattern. Even jQuery itself follows this pattern. With the ability to import global variables, your internal module code is much more robust and can safely assume that the variables you think are being referenced are, in fact, the ones being referenced. Finally, with the Module Pattern, the implementation code is much cleaner. How often have you found yourself in JavaScript copying and pasting redundant code? The Module Pattern will make your code DRY (Don't Repeat Yourself).