- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Generator Functions
JavaScript Generators & Iterators
JavaScript Generator Functions
A generator function can pause with
yieldand resume later, producing one value at a time.
Writing an iterator by hand, as in the first lesson, is fiddly to get right.
A generator writes the same thing as an ordinary-looking function.
Example
Example
javascript
function* countTo(max) {
for (let i = 1; i <= max; i++) {
yield i;
}
}
const counter = countTo(3);
console.log(counter.next());
console.log(counter.next());