Symbol Keys for Soft Privacy
You'll learn how to create properties that are harder to discover by accident using unique Symbol keys.
The Core Idea
While private class fields (#field) provide true hard privacy, Symbols offer a middle ground: "soft privacy." When you use a unique Symbol as a property key, that property won't show up in Object.keys(), for...in loops, or JSON serialization. The property isn't truly private—if someone has the Symbol itself, they can access it—but it's effectively hidden from casual enumeration and accidental access.
Think of it like storing valuables in an unmarked drawer. Someone could find it if they searched thoroughly, but most visitors won't stumble upon it.
How It Works
const _balance = Symbol('balance');
class BankAccount {
constructor(initial) {
this[_balance] = initial;
}
deposit(amount) {
this[_balance] += amount;
}
getBalance() {
return this[_balance];
}
}
const account = new BankAccount(100);
console.log(Object.keys(account)); // []
console.log(account[_balance]); // 100 (if you have the Symbol)
The property is non-enumerable and won't appear in typical object inspections. However, it's not completely hidden—Object.getOwnPropertySymbols() can reveal it, and if someone obtains your Symbol reference, they can access the property.
When to Use This
Symbol keys work well when you want to avoid naming collisions or keep implementation details out of the way without needing absolute security. They're particularly useful for internal protocol methods or metadata that shouldn't clutter an object's public interface.
Key Takeaway: Symbols provide "soft privacy" by making properties non-enumerable and hard to accidentally discover, though not truly inaccessible like private fields.