v146 · JavaScript · Iterator.concat() Demo
Iterator.concat() Demo
Combine multiple iterables — arrays, Sets, strings, generators — into a single lazy sequence. Click the buttons to run each example and see the results. The sequence is consumed one element at a time; no intermediate array is created.
Chrome 146 required for
Iterator.concat(). Older browsers will show a fallback polyfill implementation that demonstrates the same concept using a generator function.
Sync-only contract.
Iterator.concat() consumes synchronous iterables with Symbol.iterator. Async iterables, for await sources, and ReadableStream pipelines need async iteration or stream APIs instead.
basic examples
Click a button to run an example…
lazy vs eager comparison
Eager (spread into array)
// Creates 3 intermediate arrays, then merges
const result = [
...[1, 2, 3],
...[4, 5, 6],
...[7, 8, 9]
];
// ↑ Allocates full array upfront
Lazy (Iterator.concat)
// Returns an iterator — no allocation yet
const seq = Iterator.concat(
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
);
// Only materialises when consumed
code patterns
// Arrays
const seq = Iterator.concat([1, 2], [3, 4], [5, 6]);
[...seq]; // [1, 2, 3, 4, 5, 6]
// Mixed iterables
Iterator.concat(
new Set(['a', 'b', 'c']),
new Map([['x', 1], ['y', 2]]).values(),
'str' // string is iterable
).toArray();
// ['a', 'b', 'c', 1, 2, 's', 't', 'r']
// Generator function
function* range(n) { for (let i = 0; i < n; i++) yield i; }
Iterator.concat(range(3), range(3))
.map(x => x * 10)
.toArray();
// [0, 10, 20, 0, 10, 20]
// Early termination — lazy! Only reads from source until done
Iterator.concat(bigArray1, bigArray2)
.filter(x => x > 100)
.take(5) // stops after 5 matches — bigArray2 may never be read
.toArray();
// Sync-only: use Symbol.iterator sources here.
// Async iterables and ReadableStream bodies belong in async/stream pipelines.
see also
- Practical Patterns — merging search results, log streams
- ChromeStatus entry
- MDN — Iterator.concat()