Skip to main content

Object-Oriented JavaScript

Symbols and Well-Known Symbols

0:00
LearnStep 1/3

Unlocking Metaprogramming with Symbols

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.

javascript

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.

javascript

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.

javascript

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).
javascript