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.
const id = Symbol("id"); const user = { name: "Ada", [id]: 42 }; user[id]; // 42
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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...inandJSON.stringify(). Find them withObject.getOwnPropertySymbols()orReflect.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; useString(sym)orsym.description. - No implicit number conversion either:
+symthrows. - Truthy. A symbol always converts to
truein 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.toPrimitiveandSymbol.asyncIteratorlet objects customize language behavior; see well-known symbols. - Wrapper objects.
Object(sym)makes aSymbolobject; you rarely need it, andtypeofon a normal symbol is"symbol".
Browser support
Symbols are part of ES2015 and are supported in every current browser and in Node.js.