Symbols & Iterators
Symbols are unique identifiers — no two symbols are equal. They're used for creating private-like properties and built-in behaviors (Symbol.iterator). Iterators define how objects are iterated with for...of.
Symbols & Iterators
- Symbol() — Creates unique value: Symbol('desc'). Symbol('id') !== Symbol('id')
- Use case — Private-like object properties. Not shown in Object.keys() or for...in
- Symbol.iterator — Makes objects iterable with for...of
- Iterator protocol — Object with next() method returning { value, done }
- Built-in iterables — Arrays, Strings, Maps, Sets all implement Symbol.iterator
- Generators — Functions that produce iterators: function* gen() { yield 1; yield 2; }
Symbols & Iterators Code
// Symbol — unique identifier
const id1 = Symbol("id");
const id2 = Symbol("id");
console.log(id1 === id2); // false! Each symbol is unique
// Symbol as object key — hidden from iteration
const user = {
name: "Alice",
[Symbol("ssn")]: "123-456-7890" // hidden property
};
console.log(Object.keys(user)); // ["name"] — symbol not shown!
console.log(JSON.stringify(user)); // {"name":"Alice"} — symbol skipped!
// Custom iterable
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
if (current <= last) {
return { value: current++, done: false };
}
return { done: true };
}
};
}
};
for (const num of range) {
console.log(num); // 1, 2, 3, 4, 5
}
console.log([...range]); // [1, 2, 3, 4, 5]
// Generator function (shorthand for iterators)
function* fibonacci() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const fib = fibonacci();
for (let i = 0; i < 8; i++) {
console.log(`Fib ${i}: ${fib.next().value}`);
}
// 0, 1, 1, 2, 3, 5, 8, 13Tip
Tip
Use Symbol.iterator to make custom objects iterable with for...of loops. Use Symbol() for unique property keys that won't conflict with other code. Symbols are used extensively in JavaScript internals.
Symbols = unique keys. Iterators = make anything iterable.
Common Mistake
Warning
Generators pause at each yield but don't run in parallel. They're cooperative, not concurrent. Each .next() call runs until the next yield. Don't confuse generators with async behavior — they're for lazy evaluation and iteration.
Practice Task
Note
Advanced features: (1) Create a generator that yields Fibonacci numbers. (2) Make a Range class iterable with Symbol.iterator. (3) Use Proxy to create an object that logs every property access.
Quick Quiz
Key Takeaways
- Symbols are unique identifiers — no two symbols are equal.
- Symbol() — Creates unique value: Symbol('desc'). Symbol('id') !== Symbol('id')
- Use case — Private-like object properties. Not shown in Object.keys() or for...in
- Symbol.iterator — Makes objects iterable with for...of