Iterators and generators
ECMAScript 2026
An iterator reads a sequence one item at a time. A generator is a way to produce an iterator by writing a function that can pause and later continue.
On this page
Read one value with next()
An iterable is a value that offers an iterator through Symbol.iterator. Arrays are iterable. The iterator’s next() returns an object with value and done. for...of uses the same protocol to read values automatically.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
const iterator = ["Pen", "Notebook"][Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next().done);
What to expect The first results contain Pen and Notebook with done: false. The third result prints true.
Pause and resume a function with yield
A function declared with function* creates a generator when called. It starts running when next() is called and pauses at yield. Another next() call resumes it. A new generator starts the sequence again.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
function* orderNumbers(first, last) {
for (let number = first; number <= last; number += 1) {
yield number;
}
}
for (const number of orderNumbers(101, 102)) {
console.log(number);
}
What to expect The Console prints 101, then 102, and stops. Pass a first value greater than the last and the loop yields nothing.