JavaScript Iterating Maps


Example

Map has three methods which returns iterators: .keys(), .values() and .entries(). .entries() is the default Map iterator, and contains [key, value] pairs.

const map = new Map([[1, 2], [3, 4]]);

for (const [key, value] of map) {
  console.log(`key: ${key}, value: ${value}`);
  // logs:
  // key: 1, value: 2
  // key: 3, value: 4
}

for (const key of map.keys()) {
  console.log(key); // logs 1 and 3
}

for (const value of map.values()) {
  console.log(value); // logs 2 and 4
}

Map also has .forEach() method. The first parameter is a callback function, which will be called for each element in the map, and the second parameter is the value which will be used as this when executing the callback function.

The callback function has three arguments: value, key, and the map object.

const map = new Map([[1, 2], [3, 4]]);
map.forEach((value, key, theMap) => console.log(`key: ${key}, value: ${value}`));
// logs:
// key: 1, value: 2
// key: 3, value: 4