iterators only iterate once❗️

JSiterationiterator ⟩ only iterate once

iterators only iterate once❗️

💾 replit:only iterate once

// generator function returns "generators"
// - generators are "iterable iterators".
// - iterators only iterate once❗
function* genAB() {
    yield 'A';
    yield 'B';
}

// main
const ab = ['a', 'b'];     // array (iterable)
const it = ab.values();    // iterator (iterable)
const AB = genAB();        // generator (iterable iterator)

// ⭐ arrays can iterate multiple times.
[...ab, ...ab],            // [ 'a', 'b', 'a', 'b' ]

// ⭐ iterators only iterate once❗
[...it, ...it],            // [ 'a', 'b' ]❗
[...AB, ...AB],            // [ 'A', 'B' ]❗

// ⭐ have to call generator function multiple times
//    to return multiple new iterators.
[...genAB(), ...genAB()],  // [ 'A', 'B', 'A', 'B' ] ⭐

Last updated