JavaScript Symbol()
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();
Example
With description:
const id = Symbol("userId");
Symbol Type
Example
const id = Symbol();
(typeof id) // symbol
Symbols are Unique
Every Symbol value is unique.
Example
const a = Symbol("id");
const b = Symbol("id");
(a === b) // false
Symbol Descriptions
The description is only used for debugging and display purposes.
Example
const id = Symbol("userId");
(id.description) // userId
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;
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 Strinfg
| 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 |