Advertisement
Beginner JavaScript, Map, Set, WeakMap & WeakSet

How do you iterate over a Map's entries?

Short answer

A Map is directly iterable with for...of, yielding [key, value] pairs by default, matching the order items were inserted; you can also use .keys(), .values(), or .entries() explicitly.

Save JavaScript mock interview
Advertisement
AModel answer
A Map is directly iterable with for...of, yielding [key, value] pairs by default, matching the order items were inserted; you can also use .keys(), .values(), or .entries() explicitly.
const map = new Map([['a', 1], ['b', 2]]);
for (const [key, value] of map) {
  console.log(key, value); // 'a' 1, then 'b' 2
}
Real-world example
Iterating over a Map of cached API responses keyed by request URL.
Likely follow-ups
  • Does destructuring work directly in the for...of loop header like this?
Related topics