Revelling in the Revealing Module Pattern

Encapsulating Javascript code using modules.

Joshua Coquelle
5 min readJun 7, 2016

The Revealing Module Pattern is one of my favourite patterns in Javascript for controlling privacy and providing a clean API for module consumption. the Revealing Module Pattern was created by Christian Heilmann, by extending the Module Pattern to provide a more readable and consistent way of declaring your public/private functions. Another benefit is eliminating the need to constantly refer to the current ‘this’ scope of your object every time that you need to call a function.

If you’re unsure at this point why encapsulation is important in Javascript, a very high level explanation could be that having variables/methods/objects that are immutable to the public can be very important if you do not want important/sensitive internal methods or variables to be accessed, abused or mutated. Read more at https://medium.com/@joshuacoquelle/privatizing-javascript-variables-cb58efa0961#.r8xs9ijhu for more on the topic of privacy.

Now let’s take a look at the structuring of the pattern and then break it down afterwords. The Revealing Module pattern consists of essentially three basic but key elements:

1) IIFE (Immediately Invoked Function Expression) wrapper
2) Methods/Objects/Variables (module content)
3) Returned object literal

When breaking down the above elements of the pattern, we can start by looking at the IIFE. An IIFE is a function that is self calling by wrapping itself in parenthesis, followed by opening/closing parenthesis to execute the function.

/* First take an anonymous function */
function() {
}/* Wrap it in parenthesis */
(function() {
})/*
Execute the function with '()' which would log 'hi'
to the console immediately when present
*/
(function() {
console.log('hi!');
})();

Now when dealing with the contents of your IIFE module, you can declare all of your functions with a consistent syntax, rather than having your code and methods spread throughout the function body with inconsistent syntax like the original Module Pattern.

/*
In the current state of our code example, every function
expression and variable declaration are inaccessible to the
outside world.
*/
var Module = (function() {

var myPrivateFirstName = 'Joshua';
var myPrivateLastName = 'Coquelle';
/* Getters */ function getMyPrivateFirstName() {
return myPrivateFirstName;
}
function getMyPrivateLastName() {
return myPrivateLastName;
}
function getMyPrivateFullName() {
return myPrivateFirstName + ' ' + myPrivateLastName;
}
/* Setters */ function setMyPrivateFirstName(firstName) {
myPrivateFirstName = firstName;
}
function setMyPrivateLastName(lastName) {
myPrivateLastName = lastName;
}
})();

Here we have created our module (cleverly named “Module”), containing an Immediately Invoked Function Expression (IIFE) with a function body of variables and methods for getting and setting my first and last name. If you tried to execute this code in your browser console to play with the module you would hit a brick wall.

/* Try to log out a function from within the module */Module.getMyPrivateFirstName();Uncaught TypeError: Cannot read property 'getMyPrivateFirstName' of undefined/* Try to log out a variable containing first name as string */Module.myPrivateFirstName;Uncaught TypeError: Cannot read property 'myPrivateFirstName' of undefined

As you can see, because of our closure scope which is created by the IIFE, we have no access whatsoever to any of Module’s content. This brings us to the final key piece of our Revealing Module puzzle; Returning the object literal.

Returning an object literal at the end of our IIFE allows us to expose a public API to access contents within the module. Apart from just exposing these properties, we also can give cleaner/more concise names to our API methods. For example, we can have extremely explicit naming within our module for readability sake, yet when returning the object we can clean up the naming that will be used by our API.

var Module = (function() {

var myPrivateFirstName = 'Joshua';
var myPrivateLastName = 'Coquelle';
/* Getters */ function getMyPrivateFirstName() {
return myPrivateFirstName;
}
function getMyPrivateLastName() {
return myPrivateLastName;
}
function getMyPrivateFullName() {
return myPrivateFirstName + ' ' + myPrivateLastName;
}
/* Setters */ function setMyPrivateFirstName(firstName) {
myPrivateFirstName = firstName;
}
function setMyPrivateLastName(lastName) {
myPrivateLastName = lastName;
}
/* Expose our public API with concise naming */ return {
getFirstName: getMyPrivateFirstName,
getLastName: getMyPrivateLastName,
getFullName: getMyPrivateFullName,
setFirstName: setMyPrivateFirstName,
setLastName: setMyPrivateFirstName
}
})();

Now that we have exposed our API, we can call on Module’s methods and they are publicly available for us to utilize, yet if we tried to call the private properties we will still get errors.

/* Attempting to access private vars/methods */Module.getMyPrivateFirstName();
// Uncaught TypeError: Cannot read property 'getMyPrivateFirstName' of undefined
Module.setMyPrivateFirstName('Josh');
// Uncaught TypeError: Cannot read property 'setMyPrivateFirstName' of undefined

Damn, no access GRRRR!

/* Accessing via public API */Module.getFirstName();
// 'Joshua'
Module.setFirstName('Josh');Module.getFirstName();
// 'Josh'

It works!

And there you have it, thanks to our Revealing Module Pattern, we have been able to:

  • Have complete control over module privacy
  • Utilize a consist syntax throughout our module
  • Avoided having to refer to ‘this’ when calling functions
  • Created a safe closure scope to avoid variable naming collisions
  • Allowed expressing naming conventions for readability, then exposed the methods with more concise naming
  • Exposed only what we wanted to reveal for our modules API

I hope you enjoyed learning a little more about Javascript design patterns and the Revealing Module Pattern specifically. As I said at the beginning of this article, this pattern remains to be one of my favourite design patterns for encapsulating my code into small modules and can even be used as a pattern for creating libraries by exposing a constructor function to allow for instantiation. Thanks for Reading!

Until next time.

--

--

Joshua Coquelle

Developer. Alpaca Aficionado. Corgi owner. Technical blogging for beginner to intermediate Javascript developers.