Iterating maps

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Map:
* Syntax
* Iterating maps

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde