UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ Iterator/ Iterator.prototype.forEach()

The forEach() method of Iterator instances is similar to Array.prototype.forEach: it executes a provided function once for each element produced by the iterator.

Syntax

forEach(callbackFn)

Parameters

Return value

undefined.

Description

forEach() iterates the iterator and invokes the callbackFn function once for each element. Unlike most other iterator helper methods, it does not work well with infinite iterators, because it is not lazy.

Examples

Using forEach()

new Set([1, 2, 3]).values().forEach((v) => console.log(v));

// Logs:
// 1
// 2
// 3

This is equivalent to:

for (const v of new Set([1, 2, 3]).values()) {
  console.log(v);
}

Specifications

Browser compatibility

See also