Summary - Symbol
Add a private property to an object that is invisible to for...in using Symbol.
Summary: Symbol
Symbol is JavaScript's seventh primitive: unique, immutable, and hidden from for...in. Symbol() makes a fresh value each call; Symbol.for() shares one via the global registry.
Well-known symbols (Symbol.iterator, Symbol.toPrimitive, Symbol.toStringTag) hook into language behavior. Symbol keys are ideal for internal metadata and enum categories, because they cannot collide with string keys.
When should you use symbols?
There are three main reasons to use symbols: (1) unique values that cannot accidentally collide (enum categories), (2) attaching metadata to objects you do not fully control (libraries), (3) hooking into language behavior (well-known symbols).
Do not use symbols for general object properties; they make debugging harder and disappear during serialization. Symbols shine when they serve a specific purpose.
Exercise Attach extension-safe metadata
Create a symbol named internal. Add a string key count: 0 and a symbol key [internal]: { ttl: 60 } to the cache object. Walk cache with for...in and log the string keys. Then collect and log the symbol keys.
Show example solution
const internal = Symbol('internal');
const cache = {
count: 0,
[internal]: { ttl: 60 }
};
for (let key in cache) {
console.log(key);
}
console.log(Object.getOwnPropertySymbols(cache));
Test yourself
-
A library wants to attach hidden metadata to a user's object. Which way is safest?
- Use a string key; it appears in for...in
- Use a string key with the same name; risk of collision
- Use a symbol key; it stays hidden in for...in
- Add a string to the prototype
Show answer
Use a symbol key; it stays hidden in for...in — Correct. Symbol keys stay hidden from for...in and Object.keys; no name collision.
-
Show equality with a shared symbol
const shared = ____; const other = Symbol.for('shared'); console.log(shared === other);Show answer
const shared = Symbol.for('shared'); const other = Symbol.for('shared'); console.log(shared === other);