Programming Languages JavaScript Subjective
Sep 25, 2025

What are JavaScript Generators and Iterators?

Detailed Explanation

Generators are functions that can pause and resume execution, producing a sequence of values.

Generator Function:


function* numberGenerator() {
yield 1;
yield 2;
yield 3;
return "done";
}

const gen = numberGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: "done", done: true }

Infinite Sequences:


function* fibonacci() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}

const fib = fibonacci();
console.log(fib.next().value); // 0
console.log(fib.next().value); // 1
console.log(fib.next().value); // 1

Iterator Protocol:


const iterable = {
[Symbol.iterator]() {
let count = 0;
return {
next() {
if (count < 3) {
return { value: count++, done: false };
}
return { done: true };
}
};
}
};

for (const value of iterable) {
console.log(value); // 0, 1, 2
}

Use Cases:
- Lazy evaluation
- Memory-efficient sequences
- Async iteration
- State machines
- Custom iterables

Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback