Generators & Iterators: Interview Questions
JS جاوااسکریپت

Generators & Iterators: Interview Questions

Yield values lazily, build custom iterables, and explain how `for...of` works under the hood.

BugCast Admin··۵ دقیقه مطالعه

Generators are functions that can pause and resume, producing a sequence of values. They power lazy evaluation patterns and async flows before async/await dominated.

Common Interview Questions

Q: What does a generator function return?

Answer: Calling a generator returns an iterator object with a next() method. Each yield pauses execution and returns { value, done }.


function* range(n) {
  for (let i = 0; i < n; i++) yield i;
}
const it = range(3);
it.next(); // { value: 0, done: false }

Q: How do you make a custom iterable?

Answer: Implement [Symbol.iterator]() returning an object with next(). for...of and spread use this protocol.


const collection = {
  items: [1, 2, 3],
  [Symbol.iterator]() {
    let i = 0;
    const items = this.items;
    return {
      next() {
        return i < items.length
          ? { value: items[i++], done: false }
          : { done: true };
      },
    };
  },
};

Q: What is yield* used for?

Answer: Delegates iteration to another iterable or generator, flattening nested sequences without manual loops.

Q: Generators vs async generators?

Answer: Async generators (async function*) yield Promises and work with for await...of. Useful for paginated APIs and streaming data.

Key Points for Interviews

  • Generators are pausable functions with lazy evaluation

  • Iterables implement Symbol.iterator

  • next() can receive values via iterator.next(val) after yield

  • Infinite sequences are safe with generators (not with arrays)

  • Less common post-async/await but still asked at senior level

#generators#iterators#interview

مطالب مرتبط