JavaScript theorytheory 0/50 · 0%
Arrays · medium

24. Iteration and generators

for...of, iterables and lazy sequences.

`for...of` walks any iterable — arrays, strings, Maps, Sets. `for...in` walks keys and should be avoided on arrays. Generators produce values lazily with `yield`.

function* blocks(from, to) {
  for (let n = from; n <= to; n++) yield n;
}
for (const n of blocks(1, 3)) console.log(n);

Generators are ideal for paging RPC results without buffering everything in memory.

Check your understanding

  1. 1. What does `for...in` iterate?

  2. 2. What does `yield` do?

  3. 3. Why use a generator for paging?