Hiding Internal Properties with Symbols
You'll learn how to use symbols to store metadata or private-like data that won't show up in normal iteration or property listing.
Why Hide Properties?
Sometimes you need to attach metadata to an object—counters, internal state, or configuration—without polluting the object's visible interface. String keys appear in for...in loops, Object.keys(), and JSON serialization. Symbols offer a cleaner solution.
How Symbols Hide Data
Since symbols aren't enumerable by default, they're invisible to most object inspection methods. This makes them perfect for "internal" properties that users of your object shouldn't accidentally encounter or modify.
const _internalCounter = Symbol('counter');
const widget = {
name: 'Button',
[_internalCounter]: 0,
click() {
this[_internalCounter]++;
console.log('Clicked!');
},
getStats() {
return `Clicked ${this[_internalCounter]} times`;
}
};
console.log(Object.keys(widget)); // ['name', 'click', 'getStats']
console.log(widget.name); // 'Button'
console.log(widget.getStats()); // 'Clicked 0 times'
widget.click();
widget.click();
console.log(widget.getStats()); // 'Clicked 2 times'
// The counter is hidden from normal iteration
for (let key in widget) {
console.log(key); // Only logs: name, click, getStats
}
The _internalCounter symbol stores data without cluttering the object's public interface. Users see name, click, and getStats, but not the internal tracking mechanism.
Key Takeaway: Use symbols as object keys to store metadata or internal state that shouldn't appear in Object.keys(), for...in, or JSON serialization, creating a cleaner separation between public and internal properties.