1. What is a Symbol?
A Symbol is a unique and immutable primitive value introduced in ES6. Unlike strings or numbers, no two Symbols are the same, even if they have the same description.
- Purpose: They are mostly used to create unique property keys for objects to avoid property name collisions.
2. Creating a Symbol
You create a Symbol using the Symbol() function:
const sym1 = Symbol();
const sym2 = Symbol('mySymbol');
console.log(sym1); // Symbol()
console.log(sym2); // Symbol(mySymbol)
console.log(sym1 === sym2); // false (always unique)
- Optional description is only for debugging; it doesn’t affect uniqueness.
3. Symbols as Object Keys
Symbols can be used as property keys:
const mySymbol = Symbol('id');
const user = {
name: 'Alice',
[mySymbol]: 12345 // Symbol key
};
console.log(user.name); // Alice
console.log(user[mySymbol]); // 12345
- Notice the square brackets
[mySymbol]are required when using a Symbol as a key. - Symbol-keyed properties don’t show up in
for...inloops orObject.keys().
4. Global Symbols
You can create symbols that are shared across different parts of the code using Symbol.for():
const globalSym1 = Symbol.for('app.id');
const globalSym2 = Symbol.for('app.id');
console.log(globalSym1 === globalSym2); // true
Symbol.for()looks up a global symbol registry and returns the existing symbol if it exists; otherwise, it creates a new one.- Use
Symbol.keyFor()to get the key from a global symbol:
console.log(Symbol.keyFor(globalSym1)); // "app.id"
5. Why Use Symbols?
- Unique property keys: Avoid conflicts in large codebases or libraries.
- Hidden properties: Symbols are not enumerable in loops.
- Well-known Symbols: JavaScript uses predefined symbols like
Symbol.iteratororSymbol.toStringTagfor internal behaviors.
Example with Symbol.iterator:
const iterableObj = {
[Symbol.iterator]: function* () {
yield 1;
yield 2;
yield 3;
}
};
for (const value of iterableObj) {
console.log(value); // 1 2 3
}
✅ Summary:
- Symbol is a unique, immutable primitive.
- Mainly used as object keys to avoid naming collisions.
- Symbols can be local (
Symbol()) or global (Symbol.for()). - Many built-in Symbols exist for customizing behavior.
