JavaScript Symbol()
The Symbol() Function
The Symbol() function creates Symbol values.
A Symbol is a unique and immutable primitive value.
Symbols are commonly used as unique property keys.
Syntax
Symbol()
Symbol(description)
Parameters
| Parameter | Description |
|---|---|
| description | Optional. A string description for the symbol. |
Return Value
| Call | Returns |
|---|---|
Symbol() |
A primitive symbol value |
Creating Symbols
Example
const id = Symbol();
With description:
const id = Symbol("userId");
Symbol Type
Symbols are Unique
Every Symbol value is unique.
Symbol Descriptions
The description is only used for debugging and display purposes.
Symbols as Object Keys
Symbols can be used as object property keys.
This is probably the most practical use case.
Example
const id = Symbol("id");
const person = {
name: "John"
};
person[id] = 123;
Try it Yourself »
Global Symbols
The Symbol.for() method creates or retrieves a shared global symbol.
Example
const a = Symbol.for("id");
const b = Symbol.for("id");
(a === b) // true
Symbol vs String
| Symbol | String |
|---|---|
| Always unique | Can have duplicate values |
| Primitive type: symbol | Primitive type: string |
| Often used as object keys | Often used as text values |
No Constructor
Symbol() is not a constructor.
The new keyword cannot be used with Symbol().
Example
new Symbol("id"); // TypeError
Well-Known Symbols
JavaScript provides built-in well-known symbols that customize object behavior.
Symbol.iteratorSymbol.asyncIteratorSymbol.toStringTagSymbol.hasInstance
Type Information
| Property | Value |
|---|---|
| Callable | Yes |
| Constructible | No |
| Returns | Primitive symbol values |
| Primitive Type | symbol |
| Unique Values | Yes |
Browser Support
Symbol() is an ECMAScript6 (ES6 2015) feature.
JavaScript 2015 is supported in all browsers since June 2017:
| Chrome 51 |
Edge 15 |
Firefox 54 |
Safari 10 |
Opera 38 |
| May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |