Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Iterators, Generators and Symbols

The Symbol primitive

Reference for the JavaScript Symbol type: creating unique symbols, descriptions, using them as property keys, hidden properties, and string conversion rules.

A symbol is a primitive value that is guaranteed to be unique. You create one by calling Symbol(); every call returns a new symbol that is not equal to any other, even if the optional description is the same.

Symbols are mostly used as property keys that cannot collide with strings or with other code's keys, and for the language's own hooks such as Symbol.iterator. They are also handy as private-ish constants, such as unique enum members.

JavaScript
const id = Symbol("id");
const user = { name: "Ada", [id]: 42 };
user[id]; // 42

Try it

JS Unique keys and hidden properties

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Conversion rules and enums

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Symbol()
Symbol(description)
Name Description
description Optional. A label for debugging. It is converted to a string and does not make the symbol unique.

Return value: a new unique symbol.

Exceptions: new Symbol() throws a TypeError; Symbol is a function, not a constructor.

Instance members

Member Description
symbol.description The description string, or undefined if none was given.
symbol.toString() A string such as Symbol(tag).
symbol.valueOf() The symbol itself.

Usage notes

  • Equality is identity. Two symbols are equal only if they are the same symbol. To share a symbol across files or realms, use Symbol.for().
  • Symbol keys are skipped by Object.keys(), Object.entries(), for...in and JSON.stringify(). Find them with Object.getOwnPropertySymbols() or Reflect.ownKeys(). This is "hidden", not private: anyone with the object can still list the symbols.
  • No implicit string conversion. Concatenating or interpolating a symbol throws a TypeError; use String(sym) or sym.description.
  • No implicit number conversion either: +sym throws.
  • Truthy. A symbol always converts to true in a boolean context.
  • Computed keys. In object literals and classes, symbol keys need square brackets: { [id]: 1 }.
  • Use as constants. Symbols make safe enum-like values because they cannot be forged by passing a lookalike string, as the "green" case above shows.
  • Well-known symbols such as Symbol.iterator, Symbol.toPrimitive and Symbol.asyncIterator let objects customize language behavior; see well-known symbols.
  • Wrapper objects. Object(sym) makes a Symbol object; you rarely need it, and typeof on a normal symbol is "symbol".

Browser support

Symbols are part of ES2015 and are supported in every current browser and in Node.js.