TypeOfNaN

The Revealing Module Pattern in JavaScript

Nick Scialli
April 27, 2020

You can use the revealing module pattern in JavaScript to maintain private information using closures while exposing only what you need.

The Problem

Let’s consider the following example where we create the object clarkKent.

const clarkKent = {
  name: 'Clark Kent',
  secretIdentity: 'Superman',
  introduce: function () {
    return `Hi, my name is ${this.name}.`;
  },
  issuesReport: function () {
    return `${this.secretIdentity} saves the day!`;
  },
};

Using this example, Clark can introduce himself and can report that Superman saved the day:

console.log(clarkKent.introduce());
// Hi, my name is Clark Kent.
console.log(clarkKent.issuesReport());
// Superman saves the day!

This is great, but, oh no! We have access to Clark’s secret identity!

console.log(clarkKent.secretIdentity);
// Superman

The Revealing Module Pattern to the Rescue

One way we can get around this issue is by using the revealing module pattern. The revealing module pattern uses an Immediately Invoked Function Expression (IIFE) to create closure around variables we want access to within the module but don’t want to expose to the works.

Let’s see how this works out for Clark.

const clarkKent = (function () {
  const name = 'Clark Kent';
  const secretIdentity = 'Superman';
  const introduce = function () {
    return `Hi, my name is ${name}`;
  };
  const issuesReport = function () {
    return `${secretIdentity} saves the day!`;
  };

  return { introduce, issuesReport };
})();

console.log(clarkKent.introduce());
// Hi, my name is Clark Kent.
console.log(clarkKent.issuesReport());
// Superman saves the day!
console.log(clarkKent.secretIdentity);
// undefined

Perfect! We’ve created a closure around the secret information we don’t want to expose and only revealed the introduce and issuesReport methods from our module!

Conclusion

While this is a bit of a silly example, it’s important to note that we have tools and patterns at our exposure to maintain privacy and, importantly, not expose imformation beyond where it’s really needed.

Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli