JavaScript Symbol Primitive
A symbol primitive represents a unique identifier.
The type name is symbol.
Symbol values are one of JavaScript's 7 primitive types.
Why Symbols Exist
Symbols provide unique values that can be used as property keys.
No two symbols are equal unless they refer to the same symbol value.
Creating Symbols
Use the Symbol() function to create a symbol.
Example
const id = Symbol();
You can optionally provide a description.
Example
const id = Symbol("userId");
Type Information
The primitive type of a symbol value is symbol.
Symbols Are Unique
Every call to Symbol() creates a new unique value.
Example
const a = Symbol("id");
const b = Symbol("id");
document.getElementById("demo").innerHTML = (a === b);
The result is:
false
The descriptions are the same, but the symbols are different values.
Symbol Descriptions
A symbol description is used for debugging and display purposes.
The description does not affect symbol uniqueness.
Example
const id = Symbol("userId");
document.getElementById("demo").innerHTML = id.description;
The result is:
userId
Symbols as Property Keys
Symbols are commonly used as object property keys.
Example
const id = Symbol("id");
const person = {
name: "John"
};
person[id] = 123;
The symbol key does not conflict with string property names.
Global Symbols
The Symbol.for() method creates or retrieves a symbol from the global symbol registry.
Example
const a = Symbol.for("id");
const b = Symbol.for("id");
document.getElementById("demo").innerHTML = (a === b);
The result is:
true
Unlike Symbol(), Symbol.for() can return an existing symbol.
Well-Known Symbols
JavaScript provides several built-in symbols that customize object behavior.
| Symbol | Purpose |
|---|---|
Symbol.iterator |
Defines iteration behavior |
Symbol.asyncIterator |
Defines async iteration behavior |
Symbol.toStringTag |
Customizes object type strings |
Symbol.hasInstance |
Customizes instanceof behavior |
Well-known symbols are used by JavaScript itself.
Symbols and Iterables
Iterables use Symbol.iterator.
Example
const iterator = [1,2,3][Symbol.iterator]();
See JavaScript Iterables.
No Constructor
Symbol is not a constructor.
The new keyword cannot be used with Symbol.
Example
new Symbol("id");
The example throws a TypeError.
Symbol vs String
| Symbol | String |
|---|---|
| Always unique | May have duplicate values |
| Primitive type: symbol | Primitive type: string |
| Often used as property keys | Often used as text values |
Summary
| Property | Value |
|---|---|
| Primitive Type | symbol |
| Unique Values | Yes |
| Constructible | No |
| Global Registry | Yes (Symbol.for) |