Symbol.iterator
In one line
Symbol.iterator is the well-known symbol that defines an object's default iterator, enabling for...of and spread syntax.
In simple words
Symbol.iterator is a well-known symbol that marks a method as the default iterator for an object. When you write for...of, use the spread operator, or call Array.from on an object, the engine looks for [Symbol.iterator] and calls it to get an iterator.
An iterator is an object with a next() method returning { value, done }. By defining [Symbol.iterator] on your own objects, you make them iterable — they work with for...of, spread (...obj), destructuring, and Array.from. This is how arrays, strings, Maps, Sets, and generators are all iterable.
For example, a custom Range object can implement [Symbol.iterator] to yield each number in the range, and then for (const n of range) works. Generators are a concise way to implement iterators — a generator function assigned to [Symbol.iterator] returns an iterator automatically.
Example
class Range {
constructor(start, end) { this.start = start; this.end = end; }
[Symbol.iterator]() {
let cur = this.start, end = this.end;
return { next() {
return cur <= end ? { value: cur++, done: false } : { done: true };
}};
}
}
for (const n of new Range(1, 5)) console.log(n); // 1 2 3 4 5
console.log([...new Range(1, 3)]); // [1, 2, 3]Range defines [Symbol.iterator] returning an iterator object. Now for...of and spread work on Range instances.
Related terms
Related Resources
Related Lessons
- Iterables
Learn Symbol.iterator.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.