Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. Iterator
  6. map()

Iterator.prototype.map()

Baseline 2025
Newly available

Since ⁨March 2025⁩, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Themap() method ofIterator instances returns a newiterator helper object that yields elements of the iterator, each transformed by a mapping function.

Syntax

js
map(callbackFn)

Parameters

callbackFn

A function to execute for each element produced by the iterator. Its return value is yielded by the iterator helper. The function is called with the following arguments:

element

The current element being processed.

index

The index of the current element being processed.

Return value

A newiterator helper object. Each time the iterator helper'snext() method is called, it gets the next element from the underlying iterator, appliescallbackFn, and yields the return value. When the underlying iterator is completed, the iterator helper is also completed (thenext() method produces{ value: undefined, done: true }).

Description

The main advantage of iterator helpers over array methods is that they are lazy, meaning that they only produce the next value when requested. This avoids unnecessary computation and also allows them to be used with infinite iterators. Themap() method allows you to create a new iterator that, when iterated, produces transformed elements.

Examples

Using map()

The following example creates an iterator that yields terms in the Fibonacci sequence, transforms it into a new sequence with each term squared, and then reads the first few terms:

js
function* fibonacci() {  let current = 1;  let next = 1;  while (true) {    yield current;    [current, next] = [next, current + next];  }}const seq = fibonacci().map((x) => x ** 2);console.log(seq.next().value); // 1console.log(seq.next().value); // 1console.log(seq.next().value); // 4

Using map() with a for...of loop

map() is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with afor...of loop:

js
for (const n of fibonacci().map((x) => x ** 2)) {  console.log(n);  if (n > 30) {    break;  }}// Logs:// 1// 1// 4// 9// 25// 64

This is equivalent to:

js
for (const n of fibonacci()) {  const n2 = n ** 2;  console.log(n2);  if (n2 > 30) {    break;  }}

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-iterator.prototype.map

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp