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.
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.
Note
Even if the descriptions ("id1") are the same, the symbols are different values.
Symbol Descriptions
A symbol description is used for debugging and display purposes.
The description does not affect symbol uniqueness.
Symbols as Property Keys
Symbols are commonly used as object property keys.
Example
const id = Symbol("id");
const person = {
name: "John"
};
person[id] = 123;
Try it Yourself »
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.
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]();
Learn More:
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 | Can have duplicate values |
| Primitive type is symbol | Primitive type is string |
| Often used as property keys | Often used as text values |