JS: Iterator.prototype.forEach

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2025)

iterator.forEach(f)

f is passed args: currentElement, currentIndex.

similar to Array.prototype.forEach

// define a generator function
function* gf() {
 for (let x of Array(4).fill(0)) yield x;
}

// create a generator. a generator is both iterable and iterator
const xgen = gf();

// use method forEach
const xresult = xgen.forEach((x, i) => console.log(x, i));
/*
0 0
0 1
0 2
0 3
*/

console.assert(xresult === undefined);