TypeOfNaN

The Revealing Module Pattern in JavaScript

Nick Scialli
April 27, 2020

New — Check out my free newsletter on how the web works!

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.

🎓 Learn how the web works

One of the best ways to level up your tech career is to have a great foundational understanding of how the web works. In my free newsletter, How the Web Works, I provide simple, bite-sized explanations for various web topics that can help you boost your knowledge. Join 2,500+ other learners on the newsletter today!

Signing up is free, I never spam, and you can unsubscribe any time. You won't regret it!

Sign up for the newsletter »
Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli