Symbol
MediumIn plain terms
Symbol creates unique identifiers. Every Symbol() is unique. Used for object property keys to avoid collisions. Symbol.iterator defines iteration. Primitives, not objects.
What you need to know
- •Unique every time
- •Used for hidden/private keys
- •Symbol.iterator, etc.
Try it yourself
Copy the code below and run it in your browser console or a code editor:
const id1 = Symbol();
const id2 = Symbol();
id1 === id2; // false
const ID = Symbol('id');
const user = {
[ID]: 123,
name: 'Alice'
};
user[ID]; // 123
// Well-known symbols
const obj = {
[Symbol.iterator]: function*() {
yield 1;
yield 2;
}
};Learn more
Dive deeper with these trusted resources: