Symbols are a unique primitive type introduced in ES6, primarily used as unique identifiers for object properties. Unlike strings, every symbol created with Symbol() is unique, preventing property name collisions.
Creating Symbols
You create a symbol by calling the function. You can provide an optional description for debugging.
Symbols as Object Keys
Symbols can serve as object keys. These properties are not enumerable in standard loops (like for...in), offering a form of 'hidden' property.
The Global Registry
To share symbols across different parts of your codebase (or even across realms/iframes), use Symbol.for(). It checks the global registry first before creating a new one.
Well-Known Symbols
JavaScript exposes several built-in symbols that let you hook into core language behaviors.
- Symbol.iterator: Defines the default iterator for an object. Used by
for...of loops. - Symbol.toPrimitive: customize how an object is converted to a primitive value (string, number, or default).