๐ŸŸก MediumEvent Loop & Promises๐Ÿ’ป Output Question

Custom iterable with for...of

๐Ÿ’ก

Hint

[Symbol.iterator] is called fresh each time the object is iterated โ€” making the iterable reusable. The returned iterator is the stateful part.

What does this output?

const range = {
  start: 1,
  end: 4,
  [Symbol.iterator]() {
    let current = this.start;
    const end = this.end;
    return {
      next() {
        return current <= end
          ? { value: current++, done: false }
          : { value: undefined, done: true };
      }
    };
  }
};

console.log([...range]);
for (const n of range) process.stdout.write(n + ' ');

Correct Output

[1, 2, 3, 4]
1 2 3 4

Why this output?

Explanation: The range object has [Symbol.iterator] so it's iterable. Spread and for...of both call it. Each call creates a fresh iterator from start, so the range is reusable.

Key Insight: [Symbol.iterator] is called fresh each time the object is iterated โ€” making the iterable reusable. The returned iterator is the stateful part.

More Event Loop & Promises Output Questions

๐ŸŸก MediumClassic setTimeout vs Promiseโ†’๐Ÿ”ด HardNested setTimeout and Promiseโ†’๐ŸŸก Mediumasync/await execution orderโ†’๐Ÿ”ด HardPromise chaining orderโ†’

Practice predicting output live โ†’

66 output questions with instant feedback

๐Ÿ’ป Try Output Quiz