Lesson 85 - JavaScript Symbols – Creating Unique Identifiers
Symbols are a primitive data type introduced in ES6. They are unique and immutable, and are often used to create unique object keys that won’t collide with other keys or properties.
What is a Symbol?
A Symbol
is a unique and immutable value. Even if two symbols have the same description, they are not equal.
const sym1 = Symbol('id');
const sym2 = Symbol('id');
console.log(sym1 === sym2); // false
Creating Symbols
const uniqueKey = Symbol();
const anotherKey = Symbol('description'); // optional description
Using Symbols as Object Keys
const user = {
name: "Alice",
age: 30
};
const uid = Symbol("userID");
user[uid] = 101;
console.log(user); // Symbol won’t appear in normal enumeration
console.log(user[uid]); // 101
Symbols and Property Privacy
Symbols can help create semi-private object properties:
const password = Symbol("password");
const user = {
name: "Bob",
[password]: "secret123"
};
console.log(user.password); // undefined
console.log(user[password]); // "secret123"
Symbol Keys are Not Enumerable
Symbol properties are not included in for...in
or Object.keys()
:
for (let key in user) {
console.log(key); // only logs "name"
}
console.log(Object.keys(user)); // ["name"]
console.log(Object.getOwnPropertySymbols(user)); // [Symbol(password)]
Use Cases for Symbols
- Creating unique constants
- Avoiding naming collisions in object keys
- Implementing internal object properties
- Creating semi-private fields
Summary
- Symbols are unique, immutable primitive values.
- Use them as unique object keys.
- They are not included in standard property enumeration.
- Great for avoiding key collisions and creating internal/private properties.
Try Your Hand
Create a user object with a symbol-based key called userSecret
and store a secret string. Then write code to print the secret using the symbol.