JS: Iterator.prototype.map

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2025)

iterator.map(f)

Normally you can use this method on any Iterable, because all standard iterable objects are also Iterator.

  • f is given args:
  • currentElement
  • currentIndex

similar to JS: Array.prototype.map

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

// create a generator
const gg = gf();

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

// convert to array
console.log(
  JSON.stringify(Array.from(hh)) === "[[0,0],[1,1],[2,2],[3,3],[4,4]]",
);
// true

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

JavaScript. iterator helpers