JS: Iterator.prototype.map

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2025)

iterator.map(f)

f is passed args: currentElement, currentIndex.

// define a generator function
function* gf() {
 for (let x of [0, 1, 2]) yield x;
}

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

// use method map
const xresult = xgen.map((x, i) => [x, i]);

console.log(xresult);
// Object [Iterator Helper] {}

console.log(Array.from(xresult));
// [ [ 0, 0 ], [ 1, 1 ], [ 2, 2 ] ]

// result is both iterable and iterator
console.assert(Reflect.has(xresult, Symbol.iterator));
console.assert(Reflect.has(xresult, "next"));