- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Lazy Sequences
JavaScript Generators & Iterators
JavaScript Lazy Sequences
A generator can represent a sequence that has no end, because it only computes what is asked for.
An array has to exist in memory all at once; a generator does not.
Values are produced one at a time, only when requested.
Example
Example
javascript
function* naturalNumbers() {
let n = 1;
while (true) {
yield n;
n++;
}
}
const numbers = naturalNumbers();
console.log(numbers.next().value);
console.log(numbers.next().value);
console.log(numbers.next().value);