Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Symbols are primitive unique values. Every Symbol() creates a completely unique identifier, even with the same description. Perfect for private properties!
// Each Symbol() is unique
const sym1 = Symbol();
const sym2 = Symbol();
console.log(sym1 === sym2); // false
// Even with same description
const id1 = Symbol('id');
const id2 = Symbol('id');
console.log(id1 === id2); // false
// Description is just for debugging
console.log(id1.description); // 'id'// Use as object property
const id = Symbol('id');
const user = {
name: 'Alice',
[id]: 123 // Symbol as key
};
console.log(user[id]); // 123
console.log(user.name); // Alice
// Won't clash with other properties
const otherId = Symbol('id');
user[otherId] = 456; // Different property!Creating and using symbols
const password = Symbol('password');
const email = Symbol('email');
const user = {
name: 'Alice',
[password]: 'secret123',
[email]: 'alice@example.com'
};
// Hidden from normal methods
console.log(Object.keys(user));
// ['name'] - Symbols not included!
console.log(JSON.stringify(user));
// {"name":"Alice"} - Symbols excluded!
for (const key in user) {
console.log(key); // Only 'name'
}
// But still accessible if you have the symbol
console.log(user[password]); // 'secret123'
console.log(user[email]); // 'alice@example.com'Simulating private object properties
// Symbol.for() creates/retrieves from global registry
const globalId = Symbol.for('app.id');
const sameId = Symbol.for('app.id');
console.log(globalId === sameId); // true!
// Symbol.keyFor() gets the key
console.log(Symbol.keyFor(globalId)); // 'app.id'
// Regular symbols don't have keys
const localId = Symbol('id');
console.log(Symbol.keyFor(localId)); // undefined
// Useful across modules
// module1.js
export const APP_ID = Symbol.for('app.id');
// module2.js
const APP_ID = Symbol.for('app.id');
// Same symbol!Built-in symbols for special behaviors
Using symbols for metadata that won't interfere
Every Symbol() creates a unique value
Even Symbol('id') !== Symbol('id')
Don't show in Object.keys(), for...in
Use Object.getOwnPropertySymbols()
Symbol.for(key) - Share across modulesSymbol.keyFor(sym) - Get key
Symbol.iterator, Symbol.toStringTag
Symbol.hasInstance, Symbol.toPrimitive