JavaScript Interview Question #127

What is the difference between an iterator and a generator?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

An iterator is any object that follows the iterator protocol by providing a next() method that returns objects containing value and done. A generator is a convenient language feature that automatically creates an iterator from a function containing yield expressions.

Detailed Explanation

An iterator is any object that follows the iterator protocol by providing a next() method that returns objects containing value and done. A generator is a convenient language feature that automatically creates an iterator from a function containing yield expressions.

You can implement an iterator manually, but generators usually make state management much simpler because JavaScript preserves the generator function's execution position between next() calls.

Code Example

function* range(start, end) {
    for (let i = start; i <= end; i++) {
        yield i;
    }
}

for (const value of range(1, 3)) {
    console.log(value);
}