How to Create Symbol in JavaScript: Syntax and Examples
In JavaScript, you create a symbol using the
Symbol() function, which returns a unique and immutable value. You can optionally pass a description string to Symbol() to help identify the symbol during debugging.Syntax
The basic syntax to create a symbol is using the Symbol() function. You can optionally provide a description as a string to help identify the symbol.
Symbol(): Creates a new unique symbol.Symbol(description): Creates a symbol with a description for debugging.
javascript
const sym1 = Symbol(); const sym2 = Symbol('id');
Example
This example shows how to create symbols and use them as unique keys in an object. Symbols ensure the keys do not clash with other properties.
javascript
const id = Symbol('id'); const user = { name: 'Alice', [id]: 12345 }; console.log(user.name); // Alice console.log(user[id]); // 12345 // Symbols are unique even with the same description const symA = Symbol('id'); console.log(id === symA); // false
Output
Alice
12345
false
Common Pitfalls
Common mistakes when using symbols include:
- Trying to access symbol properties with dot notation instead of bracket notation.
- Assuming symbols with the same description are equal (they are always unique).
- Using symbols as keys but forgetting they are not enumerable by default.
javascript
const sym = Symbol('key'); const obj = {}; // Wrong: obj.sym = 'value'; // This creates a string key 'sym', not a symbol key // Right: obj[sym] = 'value'; console.log(obj[sym]); // 'value'
Output
'value'
Quick Reference
| Concept | Description |
|---|---|
| Symbol() | Creates a new unique symbol |
| Symbol(description) | Creates a symbol with a description string |
| Symbol keys | Use bracket notation to access symbol properties |
| Uniqueness | Symbols are always unique, even with same description |
| Non-enumerable | Symbol properties do not show up in for...in loops |
Key Takeaways
Use
Symbol() to create unique and immutable identifiers in JavaScript.Always use bracket notation to access or assign symbol-keyed properties.
Symbols with the same description are different and unique values.
Symbol properties are not enumerable by default and won't appear in normal loops.
Descriptions help debugging but do not affect symbol uniqueness.