JavaScript Iterators & Generators
Learn to create custom iteration behaviors.
1. Iterators
An iterator is an object that defines a sequence and potentially a return value upon its termination. It has a next()
method that returns an object with value
and done
properties.
JavaScript Code
Live JavaScript representation with highlighted changes
function makeRangeIterator(start = 0, end = 5, step = 1) {let nextIndex = start;return {next: function() {if (nextIndex < end) {let result = { value: nextIndex, done: false };nextIndex += step;return result;} else {return { done: true };}}};}const it = makeRangeIterator();let result = it.next();while (!result.done) {console.log(result.value);result = it.next();}
2. Generators
Generator functions provide a powerful alternative to creating iterators. They are written using the function*
syntax and use the yield
keyword to return values.
JavaScript Code
Live JavaScript representation with highlighted changes
function* makeRangeGenerator(start = 0, end = 5, step = 1) {for (let i = start; i < end; i += step) {yield i;}}const gen = makeRangeGenerator();for (const value of gen) {console.log(value);}
Console Output