Hello again! I hope you found our first lesson on the fundamentals of Symbols insightful. We established that symbols provide unique property keys, which helps avoid name collisions, but also that these properties are discoverable with Object.getOwnPropertySymbols().
Today, we'll take that concept a significant step further. We are going to combine the uniqueness of symbols with one of JavaScript's most powerful features: closures. This will allow us to achieve a much stronger form of encapsulation than symbols alone can provide.
Your learning outcome for this lesson is to: Implement private-like properties using symbols within closures.
We will cover:
- A quick review of how closures can create private state.
- The pattern of hiding a
Symbolwithin a closure to make it inaccessible to outside code. - How to build a class that uses this pattern for robust, "private-like" properties.
- The precise level of privacy this pattern affords and its limitations.
1. A Refresher: Closures for Encapsulation
Before we add symbols to the mix, let's revisit a classic JavaScript pattern for creating private state. Given your CS background, you're likely familiar with the concept of closures—a function's ability to "remember" the variables from its lexical scope, even when the function is executed outside that scope.
This mechanism can be used to encapsulate state, making it inaccessible from the outside world.
ES-Next and Private Properties
The article 'ES-Next and Private Properties' provides excellent context for our topic. Let's start by reviewing the traditional closure-based pattern for privacy it describes.
Please read the subsection titled 'Using a Closure to Encapsulate Variables'. Pay close attention to how the width, length, and height variables are completely inaccessible from outside the function, but the inner functions (the methods) can still access them.
The key idea from that reading is that variables declared inside a function's scope (like width, length, and height in the example) are private to that scope. Only code within that scope, including functions defined there, can access them. This is the foundational principle we'll build on.
2. The Pattern: Hiding a Symbol in a Closure
We now have two concepts:
- Symbols: Unique property keys that prevent name collisions. (From last lesson)
- Closures: A mechanism to create a private scope. (From our refresher)
The problem with using only a symbol is that it's discoverable on the object instance. The problem with the classic closure pattern (especially when used with class syntax) can be inefficiency or awkward syntax, as methods might need to be redefined for every instance on the this object.
The solution is to combine them. We can use a closure to hide the symbol itself, not just the data. If outside code cannot get a reference to the symbol, it cannot access the property.
Let's see how this is implemented.
ES-Next and Private Properties
The same article demonstrates this combination beautifully. It shows how to define symbols within a module-level scope (a form of closure) that a class can use.
Now, read the next section, titled 'Symbol'. Notice how the height, width, and length symbols are defined outside the class. The class methods have access to them because they are in the same scope, but code outside this file (or scope) would not.
This pattern gives us the best of both worlds:
- We can use standard ES6
classsyntax with methods on the prototype, which is memory-efficient. - We get a strong degree of privacy because the key to our "private" data (the symbol) is not exposed globally.
3. Practical Implementation with an IIFE
A common way to create this private scope for a class is using an Immediately Invoked Function Expression (IIFE). This creates a closure, we define our symbols and the class inside it, and then we return only the class.
Let's build a User class to see this in action.
const User = (() => {
// 1. The Closure Scope:
// This symbol is a private variable within the IIFE.
// It is NOT exported and cannot be accessed from the outside.
const emailSymbol = Symbol('email');
class User {
constructor(name, email) {
this.name = name; // this is a public property
this[emailSymbol] = email; // this is our "private-like" property
}
// This public method can access the "private" property because
// the method's definition exists within the same closure scope
// as the `emailSymbol` variable.
getEmailForAdmins() {
// e.g., A privileged method for internal tools
return this[emailSymbol];
}
// A simple public method
sayHello() {
console.log(`Hello, my name is ${this.name}.`);
}
}
// 2. The Return:
// We only return the User class, not the emailSymbol.
return User;
})();
// --- Let's use the class ---
const user = new User('Satoshi', 'satoshi@example.com');
user.sayHello(); // "Hello, my name is Satoshi."
// We can call the privileged method
console.log(`Admin dashboard sees email: ${user.getEmailForAdmins()}`); // "Admin dashboard sees email: satoshi@example.com"
// --- Now, let's try to break the encapsulation ---
// 1. Can we access the property using a string key? No.
console.log(user.email); // undefined
console.log(user['email']); // undefined
// 2. Can we access the symbol variable directly? No, it's not in this scope.
// console.log(user[emailSymbol]); // ReferenceError: emailSymbol is not defined
This is quite effective. We've hidden the property from casual access and prevented any possibility of a string-based name collision.
4. What "Private-Like" Really Means
Is this property truly private? No. The term "private-like" is used for a reason. As we learned in the last lesson, Object.getOwnPropertySymbols() exists. A determined developer can still find the symbol and access the data.
// Continuing from the previous example...
// A determined actor can use reflection to find the symbol key
const symbolsOnUser = Object.getOwnPropertySymbols(user);
console.log(symbolsOnUser); // [Symbol(email)]
const stolenEmailSymbol = symbolsOnUser[0];
console.log(`Hacked email: ${user[stolenEmailSymbol]}`); // "Hacked email: satoshi@example.com"
So, what's the point? The goal of this pattern is not to create a foolproof security boundary. Instead, it serves two main purposes:
- Prevent Accidental Access: It makes it impossible to accidentally read or write the property. You have to be deliberate and use reflection APIs.
- Signal Intent: It serves as a strong, syntactical signal to other developers that a property is internal to the class's implementation and should not be relied upon or modified from the outside.
This is a significant improvement over simple underscore conventions (e.g., this._email), which are just hints that can be easily ignored. Here, the closure provides actual enforcement against accidental access.
Later in this course (Module 5), we will cover true private fields using the # syntax (e.g., #email), which were introduced in ES2022. Those are not discoverable via reflection and provide a higher level of privacy. This symbol-closure pattern, however, is a powerful technique that was the gold standard for years and is something you will encounter in many established codebases.
Test your understanding!
You have a simple BankAccount class. Your task is to refactor it so that the balance property becomes "private-like" using the symbol-closure pattern.
You should add a getBalance() method that can still access the balance. The deposit method should continue to work.
Here is the starting code:
class BankAccount {
constructor(initialBalance) {
this.balance = initialBalance; // This should be made private
}
deposit(amount) {
if (amount > 0) {
this.balance += amount;
}
}
}
How would you rewrite this class inside an IIFE to meet the requirements?
Show answer
Here is the refactored solution:
const BankAccount = (() => {
const balanceSymbol = Symbol('balance');
class BankAccount {
constructor(initialBalance) {
this[balanceSymbol] = initialBalance;
}
deposit(amount) {
if (amount > 0) {
this[balanceSymbol] += amount;
console.log(`Deposited: ${amount}. New balance: ${this[balanceSymbol]}`);
}
}
// New privileged method to get the balance
getBalance() {
return this[balanceSymbol];
}
}
return BankAccount;
})();
// --- Testing the implementation ---
const account = new BankAccount(100);
console.log(account.balance); // undefined -> Correct, it's not directly accessible
account.deposit(50); // "Deposited: 50. New balance: 150"
console.log(`Current balance is: ${account.getBalance()}`); // "Current balance is: 150"
This implementation successfully encapsulates the balance property, making it accessible only through the defined methods of the class (deposit and getBalance).
Conclusion
In this lesson, we combined two fundamental JavaScript features to create a powerful encapsulation pattern. By hiding a symbol within a closure, we can create properties that are shielded from accidental external access while remaining fully available to the class's own methods.
Key Takeaways:
- A closure can be used to create a private scope.
- By defining a Symbol inside a closure (e.g., an IIFE) and only exporting the class that uses it, the symbol variable becomes inaccessible to the outside world.
- This prevents direct access to the property via
object[symbol]because thesymbolvariable isn't available. - This creates "private-like" properties. They are not truly private because reflection methods like
Object.getOwnPropertySymbols()can still discover the key. - The primary benefit of this pattern is to prevent accidental modification and to clearly signal that a property is internal.
Next Up
We've now explored two ways symbols enhance object properties: creating unique keys and enabling private-like state. JavaScript also defines a set of "well-known symbols" that allow you to hook into and customize the language's fundamental internal operations. In our next lesson, we will investigate the first of these: Symbol.toPrimitive, and learn how to customize type coercion behavior for our objects.