Organizing your JavaScript – An introduction to modules

Module pattern
When your application grows it can easily become messy with JavaScript scattered everywhere. There isn’t any built in functionality for organizing scripts in JavaScript (though adding modules as a language feature is considered for ECMA Script 6). Fortunately you can use the module pattern. It goes something like this:

var myModule = (function() {
	// Your module code goes here
}());

Now what was that? It is an anonymous function that is invoked and the result is assigned to the variable myModule. The trick is that inside the anonymous function you can decide what you want to expose. You could say that it is a factory function for creating myModule.

Let’s elaborate the example a bit and add a counter (you can never get too many of those can you ;-)

var myModule = (function() {
	'use strict';
	var counter = 0;

	function addToCounter(number) {
		counter += number;
	}

	return {
		countUp : function() {
			addToCounter(1);
		},
		hasCounted : function(compareTo) {
			return counter >= compareTo;
		}
	};
}());

Before going into the code let’s use the module in a JavaScript console:

myModule.countUp();
myModule.hasCounted(1);
true

How does it work?
You can see that there are two parts; first you define stuff that is internal to the module (line 2-7) and then you return the parts that are going to be exposed as a public API (line 10-15). The returned functions have access to the internal stuff through the scope chain (remember JavaScript has function scope).

Sub-modules
In larger systems you probably want to split your java scripts into a more fine-grained levels with sub modules which could be placed in different files. The following example is one way of defining sub-modules:

window.myModule = window.myModule || {};
window.myModule.subModule = (function() {
	// Your module code
}());

As you know the JavaScript window object represents the browser window. Here an empty property called myModule is added to it if it doesn’t already exist (window.myModule evaluates to true if it exists). By using this strategy in all your sub-modules it doesn’t matter in what order they are included on the web-page.

Connecting the modules to your HTML
Once the code is divided into modules you will probably need to connect it to HTML elements. The common practice is to keep JavaScript code away from your HTML code and have them connected by calling init methods in the modules when the HTML has been loaded (document.ready). The init method can then register event handlers.

Asynchronous Module Definition (AMD)
When using the module pattern any dependencies are assumed to be available immediately (since the anonymous function is executed at once). To make it easier to declare dependencies between modules AMD can be used. There are several implementations available, below is an example using RequireJS:

define(['dependencyName1', 'dependencyName2'], function (dep1, dep2) {
    return function () {
        // Your module code goes here
    };
});

The idea is that you use define to register a factory function for creating the module. The dependencies are specified as an array of strings and it is up to RequireJS to resolve them and make sure that the factory function isn’t invoked until all dependencies have been resolved. See the excellent RequireJS documentation for more information.

For more in-depth information about the module pattern there is a very good article at Adequately Good – JavaScript Module Pattern: In-Depth

This Post Has 2 Comments

  1. Very interesting details you have remarked, thankyou for putting up. “Success is a journey, not a destination. The doing is often more important than the outcome.” by Arthur Ashe.

  2. Great post, what I don’t get is how to access the submodule functions inside from the parent module

    In your case

    myModule.subModule = (function() {
    function abc(){
    //some code
    }
    return {abc: abc};
    }());

    How to access abc within myModule?

Leave a Reply

Close Menu