How to write JavaScript in Revealing Module Pattern

Also available in portuguese

If you wrote javascript code your entire life using a javascript file with a lot of methods inside… stop! Learn how Revealing Module Pattern helps you to separate and organize your code.

Revealing Module Pattern means you must have a Module (like container or “class”) that encapsulates all your methods and Reveal just what you want.

var converter = function(){

     var convertToString = function(aNumber){
        if(!checkIfIsNumber (aNumber)){
           return null;
        }

        return parseNumber(aNumber);
     },

     checkIfIsNumber = function(aNumber){
       if(isNumber(aNumber)){
          return true;
       } else {
          return false;
       }
     }

     return {
       convertToString: convertToString
     }

}();

The Module “converter” above encapsulate two methods: a private method “checkIfIsNumber” and a public method “convertToString”. I am just Revealing “convertToString” method.

So the usage is:

var num = converter.convertToString(100);

The Module “converter” is self invoked, that is reason of calling “converter” directlly. If you want a Module that works like a class, remove “()” from lastline.

So the Module will be:

var converter = function(){

};

So the usage is:

var num = new converter().convertToString(100);

Cleaner, beautifull and organized!

This is it. I hope it helped.

JavaScript Revealing Module Pattern

Revealing Module Pattern: Questions, suggestions and feedbacks will be appreciated. Good luck!

Do complete download of the source code on github.
About the Author:
He works as a solution architect and developer, has more than 16 years of experience in software development on several platforms and more than 14 years only for the insurance market.