Symbols
Symbol is a primitive data type introduced in ES6. A Symbol is a unique and immutable identifier.
1. Creating Symbols
You create a symbol using the Symbol() factory function. You can pass an optional description string.
const sym1 = Symbol();
const sym2 = Symbol("foo");
const sym3 = Symbol("foo");
console.log(sym2 === sym3); // false
Every Symbol() call is guaranteed to return a unique Symbol. Even if they have the same description, they are different values.
2. Use Cases
Unique Object Keys
Symbols are often used as property keys in objects to avoid name collisions.
const id = Symbol("id");
const user = {
name: "John",
[id]: 123
};
console.log(user[id]); // 123
"Hidden" Properties
Symbol properties do not appear in for...in loops or Object.keys().
for (let key in user) {
console.log(key); // "name" (id is skipped)
}
console.log(Object.keys(user)); // ["name"]
However, they are not truly private. You can access them using Object.getOwnPropertySymbols(user).
3. Global Symbol Registry
Usually, symbols are unique. However, sometimes you want to share a symbol across different parts of your application (or even across realms like iframes).
Symbol.for(key): Searches for a symbol with the given key in the global registry. If found, returns it. If not, creates a new one and stores it.Symbol.keyFor(sym): Returns the key for a global symbol.
4. Well-Known Symbols
JavaScript uses several built-in symbols to define language-internal behavior. You can use these to customize how your objects behave.
Symbol.iterator: A method that returns the default iterator for an object. Used byfor...of.Symbol.toPrimitive: A method that converts an object to a primitive value.Symbol.toStringTag: A string value used for the default description of an object.
programming/javascript/vanilla/javascript programming/javascript/vanilla/data-types programming/javascript/vanilla/iterators-and-iterables