Difficulty: Intermediate
What are Symbols in JavaScript? What are well-known Symbols?
Symbol is a primitive data type introduced in ES6. Each Symbol value is guaranteed to be unique, making them ideal for:
1. Unique object property keys (no name collisions) 2. Defining object behavior with well-known Symbols 3. Creating "hidden" properties that don't show up in enumeration
Well-known Symbols define object behavior: - Symbol.iterator: Makes an object iterable (for...of) - Symbol.toPrimitive: Controls type conversion - Symbol.hasInstance: Customizes instanceof - Symbol.toStringTag: Controls Object.prototype.toString output
const sym1 = Symbol("description");
const sym2 = Symbol("description");
console.log(sym1 === sym2); // false (always unique)
console.log(typeof sym1); // "symbol"
// As object keys
const id = Symbol("id");
const user = {
name: "Alice",
[id]: 12345
};
console.log(user[id]); // 12345
console.log(Object.keys(user)); // ["name"]
console.log(JSON.stringify(user)); // {"name":"Alice"}
// Global symbol registry
const s1 = Symbol.for("shared");
const s2 = Symbol.for("shared");
console.log(s1 === s2); // true
Each Symbol() call creates a unique value. Symbol.for() uses a global registry for shared symbols.
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next() {
return current <= end
? { value: current++, done: false }
: { done: true };
}
};
}
}
const range = new Range(1, 5);
console.log([...range]);
for (const n of range) {
process.stdout.write(n + " ");
}
Symbol.iterator makes objects work with for...of loops and the spread operator.
Symbol, Primitive Types, Well-Known Symbols, Symbol.iterator