Click here to Skip to main content
15,068,645 members
Articles / Programming Languages / Javascript
Posted 29 Aug 2011

Tagged as


61 bookmarked

JavaScript Module Pattern

Rate me:
Please Sign up or sign in to vote.
4.35/5 (24 votes)
24 Apr 2013CPOL6 min read
Javascript Module pattern helps writing code in an object oriented manner with high web performance.


In this article, I will discuss one of the best coding practices in JavaScript that is known as Module Pattern.

Module Pattern is very common in the JavaScript world with its great importance. It helps us to write clean object oriented JavaScript. Module Pattern restricts the developer to create multiple Global Variables. It is always a good practice to have less number of global variables for good performance of web application. Hence this pattern increases the performance of your website, at the same time it gives the well maintainable object oriented programing practice.

What is Module Pattern

In JavaScript programing language, functions can be used as a Module. Sometimes, it is required to create a singleton object instead of creating instance of a class. Inside the module, the inner functions do have the static scope with the other defined variables and functions.

Maximum applications written in JavaScript languages are singletons only. Hence, they all are written in Module pattern.

A Module can be considered as a Singleton Class in C#. In a Module, all the variables defined are visible only in the module. Methods in a module have scope and access to the shared private data and private methods. Hence, these methods are also called as Privileged methods.

Therefore, by creating one anonymous function returns a set of privileged methods in a simple object literal format. And because of the closure principle, those privileged methods have access to the inner methods and variables of the anonymous function. We call it as a Module Pattern.

Privileged Method

In Module Pattern, you can write your private methods, private variables those you don’t want to expose to the other world and at the same time you will be able to write public and privileged methods also. The great usefulness of this pattern is that you can very well access your private methods and variables from your methods those are called as Privileged Methods.


In order to learn Module Pattern, one must be aware of Closure principle. By using closure only modular pattern becomes very useful and powerful. Closure principle says that any inner function inside a parent function has scope to the other inner function and variables although after the parent function has returned. In Module Pattern, Privileged methods have scope to the other private variables and methods of the module.

Self-executed Function

In Module Pattern, we create one Global Singleton Object by writing self-executed method. Self-executed method is an anonymous method that is being called by itself only. See the below code that explains how we can write self-executed method.

Example of Self-executed function

(function ( ) { 
    //create variable
    //var name = "rupesh";
    //create method
    //var sayName = function ( ) {
    //    alert(name);
})( );//calling this method.  

In the above code, I have one anonymous method that is declared and just after declaration it has been called by writing(); The moment we execute this JavaScript code, this method will get executed by itself only. Hence it is called a self-executed method.

Sample of Module Pattern

Having understood the idea of module pattern, self-executed method, closure now let me define the module pattern style. See the below code:

//Single Global Variable "Module"
var Module = ( function ( ) {
    var privateVariable = "some value",
        privateMethod = function ( ) {
			//do something.
    //returning one anonymous object literal that would expose privileged methods.
    return {
         //the method inside the return object are 
         //called as privileged method because it has access 
         //to the private methods and variables of the module.

         privilegedMethod : function ( ) {
            //this method can access its private variable and method 
            //by using the principle of closure. 
            alert(privateVariable); //accessing private variable.
            privateMethod( ); //calling private method
})( ); 

Here Module is the Single Global Variable that is exposed to the document. We are declaring, calling one anonymous method and assigning it to Module variable. Now we can call privilegedMethod by writing Module.privilegedMethod(); internally privileged Method of module can access its private variable and private method. Because, they come under their static scope. If we have any data or method that we don't want to expose, we can put them in private methods.

We can also write the above code in a different manner, see the below way:

//Single Global Variable "Module"
var Module = ( function ( ) {
     privateVariable = "some value"
    ,privateMethod = function ( ) {
        //do something.
    //object literal that would have privileged methods.
    ,retObject = {
         //the method inside the return object are 
         //called as privileged method because it has access 
         //to the private methods and variables of the module.
         privilegedMethod : function ( ) {
            //this method can access its private variable and method 
            //by using the principle of closure. 
            alert(privateVariable); //accessing private variable.
            privateMethod( ); //calling private method
    //returning the object.
    return retObject;
})( ); 

Public Methods don't have access to Private Methods and variables, only the privileged method inside the Module can have access because of the closure. Let's see it.

We can create the public methods in the Module by the below method:

//augmenting public method in the module
Module.publicMethod1 = function () {
    //do something...
    //However here we will not have access to the private methods of the Module.
    //We can call the privileged method of the module object from here.
    //And by the privileged method we can call or access the inner private
    // methods and variables correspondingly 
    Module.privateMethod ( ); // this is not possible.
    //calling a privileged method of module 
    Module.privilegedMethod ( ); // this can be possible.   

In the above example, the public method publicMethod1 that we augmented into the module doesn't have access to the privateMethod of the Module object. In order to access the private Methods or Variables, we can call the privileged method of the Module inside the public. This is the benefit of this pattern. In our above example, we could call Module.privilegedMethod().

Example of Module Pattern

I have created one sample .NET application, the same is attached here in this article. In that .NET Application, I have created one Module pattern JavaScript function. Let's discuss the same function. See the below code snippet:

//One Global object exposed. 
var SearchEngine = (function ( ) { 
    //Private Method.
    var luckyAlgo = function ( ){
        //create one random number.
        return Math.floor(Math.random()*11);
    //Returning the object
    return {
        //privileged method.
        getYourLuckyNumber : function ( ){
            //Has access to its private method because of closure.
            return luckyAlgo();        
} ) ( );//Self executing method.

In the above code snippet, I have one Global variable called SearchEngine. A self-executed anonymous method is assigned in to the SearchEngine variable.

SearchEngine has one Private method luckyAlgo and one Privileged Method getYourLuckyNumber. The Privileged method is being returned by encapsulating in an anonymous object. SearchEngine can be accessed globally that will have one Privileged method only. And the Privileged method can call its local method luckyAlgo, because of the principle of Closure. In the above example, if you call getYourLuckyNumber method then it will return one random number.

Creating Sub Modules

We can create the sub-module as well by augmenting our module object with a sub module. It will be again in the same module pattern fashion. See the below example, I have created one more subSearch object inside the SearchEngine object by following the same module pattern.

//Augmenting the module with submodule
SearchEngine.subSearch = (function ( ) {
   //Private variable.
   var defaultColor = "Orange";
    //private method.
    var myColorAlgo = function (num) {
            case 1:
            defaultColor ="Green";break;
            case 2:
            defaultColor ="Black";break;
            case 3:
            defaultColor ="Yellow";break;
            case 4:
            defaultColor ="White";break;
            case 9:
            defaultColor ="Red";break;
    return {
    //privileged method
        getYourLuckyColor : function(){
            //access to private variable because of closure.
            return defaultColor;

In the above example, if we call the getYourLuckyColor method, then it will give you one color name based on the random number. I know these methods are not much practical however, I could think of them only in order to explain the concept.

Extending Modules

We can extend the existing modules by wrapping it inside one new module. By doing that, we can very well access / override the existing method of the old module. See the below code:

var Module1 = ( function (oldModule) {
	//assigning oldmodule in to a local variable.
	parent = oldModule;
    //overriding the existing privileged method.
    parent.privilegedMethod = function ( ){
         //do something different by overriding the old method.
    //private method accessing privileged method of parent module.
    var privateMethod2 = function ( ) {
        parent.privilegedMethod();//can access privileged method of Module
        parent.publicMethod1(); //can access public method of Module
    return {
        newMethod : function ( ) {
          ///do something for this brand new module.
          ///use some functionality of parent module.
          /// parent.privilegedMethod( );
} )(Module);//Module object is the existing module that I want to extend. 

In the above example, I have described the advanced features of Module pattern where one can re-use the existing module by extending, augmenting and overriding.

I have passed the old existing Module object (see above in module pattern section, we have created one Module object) while calling our anonymous method and then I have assigned it into a local variable called as parent. Now, I can access the public/privileged methods of the parent Module in my private, privileged and public method of new Module1 object.

The sweetness of this pattern comes when I can also override the existing method of the old Module. And you can see, I have overridden the privilegedMethod of the Module object. Similarly, I could have overridden the public method of the Module object


I have given very simple examples. However, one can learn this pattern and create very complex coding also. You must be aware of YUI this is a great JavaScript library It is written on the principle of Module Pattern only. In my personal experience, I used to write JavaScript code more in Module Pattern and I enjoy it a lot. Now this pattern is my favorite one and I have lots of fun also. Hope this article will help you. Please give your comments and suggestions.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Rupesh Kumar Tiwari
Software Developer (Senior)
United States United States

I am a Senior Software Developer working since 2005 in Microsoft ASP.Net and related Technologies.

I work on C#, Asp.Net, MVC, RAZOR, Entity Framework, JavaScript, jQuery, HTML5, CSS3, WCF, Silverlight, WPF, MVVM, SQL, SSIS, etc. Did Function Point Analysis, WBS to estimate projects and worked on Agile Scrum team.

I enjoy on exploring new technologies by implementing and writing about them, great interest in learning Design Patterns and their implementations. I love learning, writing JavaScript; now my favorite JavaScript library is jQuery. I enjoy writing jQuery Plugins and core JavaScript. I also write Technical blogs here. You can find me on LinkedIn.

I wrote an article on Swami Vivekananda posted his audio speeches by reading them.

Comments and Discussions

QuestionMy vote is 3 Pin
Bohdan Stupak18-Apr-20 5:45
professionalBohdan Stupak18-Apr-20 5:45 
QuestionReturn the method or wrap it in a function Pin
Aravind Ramesh25-Mar-14 21:48
MemberAravind Ramesh25-Mar-14 21:48 
AnswerRe: Return the method or wrap it in a function Pin
Rupesh Kumar Tiwari31-Mar-14 3:43
MemberRupesh Kumar Tiwari31-Mar-14 3:43 
GeneralMy vote of 3 Pin
Aravind Ramesh25-Mar-14 21:32
MemberAravind Ramesh25-Mar-14 21:32 
Questionhow to pass params to Module /Module1? Pin
sudhirblr124-Apr-13 6:36
Membersudhirblr124-Apr-13 6:36 
AnswerRe: how to pass params to Module /Module1? Pin
Rupesh Kumar Tiwari24-Apr-13 7:21
MemberRupesh Kumar Tiwari24-Apr-13 7:21 
Questioncalling parent class method with caller's private data Pin
sudhirblr123-Apr-13 19:05
Membersudhirblr123-Apr-13 19:05 
AnswerRe: calling parent class method with caller's private data Pin
Rupesh Kumar Tiwari24-Apr-13 7:45
MemberRupesh Kumar Tiwari24-Apr-13 7:45 
GeneralMy vote of 1 Pin
Esiria3-Jan-12 16:05
MemberEsiria3-Jan-12 16:05 
QuestionThis code is bad, very bad. Pin
Esiria3-Jan-12 16:03
MemberEsiria3-Jan-12 16:03 
AnswerRe: This code is bad, very bad. Pin
Rupesh Kumar Tiwari24-Apr-13 7:54
MemberRupesh Kumar Tiwari24-Apr-13 7:54 
QuestionHow to pass values into the constructor. Pin
intrepid_is29-Dec-11 12:57
Memberintrepid_is29-Dec-11 12:57 
AnswerRe: How to pass values into the constructor. Pin
Rupesh Kumar Tiwari3-Jan-12 2:10
MemberRupesh Kumar Tiwari3-Jan-12 2:10 
GeneralMy vote of 2 Pin
Andrei Bozantan1-Dec-11 11:58
MemberAndrei Bozantan1-Dec-11 11:58 
QuestionHow to create multiple public methods? Pin
TinTinTiTin17-Nov-11 23:36
MemberTinTinTiTin17-Nov-11 23:36 
AnswerRe: How to create multiple public methods? Pin
Rupesh Kumar Tiwari19-Nov-11 16:10
MemberRupesh Kumar Tiwari19-Nov-11 16:10 
GeneralRe: How to create multiple public methods? Pin
TinTinTiTin21-Nov-11 19:24
MemberTinTinTiTin21-Nov-11 19:24 
GeneralRe: How to create multiple public methods? Pin
Rupesh Kumar Tiwari22-Nov-11 5:07
MemberRupesh Kumar Tiwari22-Nov-11 5:07 
QuestionMy 5 Pin
LarryShields25-Sep-11 5:40
MemberLarryShields25-Sep-11 5:40 
GeneralMy vote of 1 Pin
TejasMal2-Sep-11 6:21
MemberTejasMal2-Sep-11 6:21 
GeneralRe: My vote of 1 Pin
Rupesh Kumar Tiwari5-Sep-11 17:10
MemberRupesh Kumar Tiwari5-Sep-11 17:10 
SuggestionMore info Pin
blessy baby31-Aug-11 0:54
Memberblessy baby31-Aug-11 0:54 
GeneralRe: More info Pin
Rupesh Kumar Tiwari31-Aug-11 10:58
MemberRupesh Kumar Tiwari31-Aug-11 10:58 
GeneralRe: More info Pin
blessy baby1-Sep-11 17:34
Memberblessy baby1-Sep-11 17:34 
QuestionVery good & informative article Rupeshji Pin
akshaylife30-Aug-11 22:14
Memberakshaylife30-Aug-11 22:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.