JS Symbols
In this page:
Creating Symbols
Symbol() creates a new, completely unique value every time it's called, even if you pass the same description string — no two symbols are ever equal to each other.
Example: Creating Symbols
const s1 = Symbol("id");
const s2 = Symbol("id");
console.log(s1 === s2); // false, always unique
Symbol Properties
A symbol can be used as an object property key, and properties keyed by a symbol are hidden from normal enumeration (for...in, Object.keys), making them useful for semi-private metadata.
Example: Symbol Properties
const id = Symbol("id");
const user = { name: "Sam", [id]: 123 };
console.log(Object.keys(user)); // ["name"], symbol hidden
Symbol Descriptions
The optional string passed to Symbol(description) is purely for debugging/display purposes (shown in console output or .toString()) and has no effect on the symbol's uniqueness or identity.
Example: Symbol Descriptions
const s = Symbol("debug label");
console.log(s.toString());
console.log(s.description);
Global Symbol Registry
Symbol.for(key) looks up (or creates) a symbol in a global registry shared across your whole program, so calling it twice with the same key returns the exact same symbol — unlike Symbol().
Example: Global Symbol Registry
const a = Symbol.for("shared");
const b = Symbol.for("shared");
console.log(a === b); // true, same registry key
Well-Known Symbols
JavaScript defines built-in well-known symbols like Symbol.iterator, which objects use to opt into being iterable with for...of — a core mechanism the language itself relies on.
Example: Well-Known Symbols
const arr = [1, 2, 3];
console.log(typeof arr[Symbol.iterator]); // "function", built-in well-known symbol
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: