Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Iterator return() and early loop exit in JavaScript

83 Symbol.iterator on a class, and who stops the loop

fair

Make a block of bus seats iterable with a generator method named [Symbol.iterator], with a finally that records the close. Then count how many seats are actually produced by a spread, by a two-element destructuring, and by a for...of that breaks early — and check that the object can be iterated again afterwards.

Stuck? Three hints, smallest first
  1. 1. A generator method named [Symbol.iterator] is the whole protocol: each call returns a fresh iterator.
  2. 2. A pattern only pulls what it needs, and then tells the iterator it is finished.
  3. 3. That message is return(), and inside a generator it runs the finally block.

The answer

let produced = 0;

class SeatBlock {
  constructor(rows, perRow) {
    this.rows = rows;
    this.perRow = perRow;
    this.closes = 0;
  }

  *[Symbol.iterator]() {
    try {
      for (let r = 0; r < this.rows; r++) {
        for (let s = 1; s <= this.perRow; s++) {
          produced++;
          yield `${String.fromCharCode(65 + r)}${s}`;
        }
      }
    } finally {
      this.closes++;
    }
  }
}

const block = new SeatBlock(2, 3);

const all = [...block];
const producedBySpread = produced;

produced = 0;
const [firstSeat, secondSeat] = block;
const producedByPattern = produced;

produced = 0;
const found = [];
for (const seat of block) {
  found.push(seat);
  if (seat === 'A2') break;
}
const producedByBreak = produced;

const closesSoFar = block.closes;
const asSet = new Set(block);
const reIterable = [asSet.size, [...block].length];

const bareGenerator = block[Symbol.iterator]();
const firstPull = bareGenerator.next().value;
const drained = [...bareGenerator].length;
const secondTime = [...bareGenerator].length;

const nextButNotIterable = { next: () => ({ value: 'A1', done: false }) };
let spreadFailed;
try {
  spreadFailed = [...nextButNotIterable];
} catch (error) {
  spreadFailed = error.constructor.name;
}

console.log('all    :', all, '| produced:', producedBySpread);
console.log('pattern:', firstSeat, secondSeat, '| produced:', producedByPattern);
console.log('break  :', found, '| produced:', producedByBreak, '| closes:', closesSoFar);
console.log('bare   :', firstPull, drained, secondTime, '| not iterable:', spreadFailed);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('spread drains the whole sequence', [all, producedBySpread], [['A1', 'A2', 'A3', 'B1', 'B2', 'B3'], 6]);
test('a two-element pattern pulls exactly two', [[firstSeat, secondSeat], producedByPattern], [['A1', 'A2'], 2]);
test('and a break stops the generator where it stood', [found, producedByBreak], [['A1', 'A2'], 2]);
test('each early exit ran the finally block, so all three closes were recorded', closesSoFar, 3);
test('being iterable is all a Set constructor asks for', asSet.size, 6);
test('and every fresh call to Symbol.iterator starts again from the top', reIterable, [6, 6]);
test('a generator object, by contrast, is used up once', [firstPull, drained, secondTime], ['A1', 5, 0]);
test('an object with next but no Symbol.iterator is not iterable at all', spreadFailed, 'TypeError');

One generator method named [Symbol.iterator] buys the whole protocol: for...of, spread, array destructuring, Array.from, and the Set, Map and Promise.all constructors all speak it. Writing it by hand — an object with a next that returns { value, done } — works too, but the generator version keeps its position in ordinary control flow, which is far easier to read.

The interesting half is who stops the loop. A consumer that finishes early calls return() on the iterator, and inside a generator that unwinds to the finally, so cleanup happens on break, on an early return, on a throw in the loop body, and after a partial destructuring. That is why a pattern taking two elements from a six-element source produced exactly two and still recorded a close: the pattern pulled twice and then said it was done. Put the file handle, the cursor or the lock release in that finally and it is genuinely safe.

Note the difference between the class and a generator object. The class is iterable: every call to block[Symbol.iterator]() is a new walk, so it can be iterated as often as you like. A generator object is an iterator that also returns itself, so it can be walked once and comes back empty for ever after. If you hand a generator object to two consumers, only the first one sees anything.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.