Sub topic 1
What a Symbol Is: A Unique Primitive
A symbol is a primitive value whose only job is to be unique. You will use symbols mostly as property keys that cannot collide with any other key.
Prerequisites
This chapter assumes you know JavaScript primitive types and typeof, object property access with computed names (obj[key]), ES6 classes, and for...of with spread syntax.
Creating Symbols
You create a symbol by calling Symbol() as a function. Every call returns a new value, so two symbols are never equal, even when they share a description.
const a = Symbol('id');
const b = Symbol('id');
console.log(typeof a); // "symbol"
console.log(a === b); // false
console.log(a.description); // "id"
console.log(a.toString()); // "Symbol(id)"
// new Symbol('id'); // TypeError: Symbol is not a constructorThe description is only a label for debugging. It does not affect identity.
Descriptions and String Conversion
Explicit conversion works. Implicit conversion throws an error. JavaScript blocks implicit conversion so that you can't accidentally turn a symbol key into an ordinary string key such as "Symbol(x)".
const s = Symbol('x');
console.log(String(s)); // "Symbol(x)"
try {
console.log(s + '');
} catch (e) {
console.log(e instanceof TypeError); // true
}Symbols as Collision-Free Property Keys
When two libraries both attach an id property to the same object, one overwrites the other. A symbol key avoids this problem because no other code can produce the same key by accident. You must use bracket syntax to set or read a symbol-keyed property.
Where Symbol Keys Show Up and Where They Stay Hidden
Ordinary enumeration skips symbol keys. Reflection APIs still list them.
const id = Symbol('id');
const user = { name: 'Ada', [id]: 42 };
console.log(user[id]); // 42
console.log(Object.keys(user)); // ['name']
console.log(JSON.stringify(user)); // {"name":"Ada"}
console.log(Object.getOwnPropertySymbols(user)); // [Symbol(id)]
console.log(Reflect.ownKeys(user)); // ['name', Symbol(id)]| API | Includes symbol keys? |
|---|---|
| `Object.keys`, `for...in` | No |
| `JSON.stringify` | No |
| `Object.getOwnPropertySymbols` | Yes, symbols only |
| `Reflect.ownKeys` | Yes, strings and symbols |
Symbol keys stay out of the way of normal code, but any code can still find them through reflection. They do not make data private.
Exercise
Given const k = Symbol('k'); const o = { [k]: 1, x: 2 };, what do Object.keys(o).length and Reflect.ownKeys(o).length return, and what does Symbol('k') === k return?
Show answer
Object.keys(o).length is 1 because it skips the symbol key. Reflect.ownKeys(o).length is 2 because it includes both keys. Symbol('k') === k is false because every call to Symbol() creates a new, unique value.