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

#javascript #module pattern #programming

The Revealing Module Pattern in JavaScript
1.45 GEEK