Back to results for “WeakMap & WeakSet”
JavaScript › Map, Set, WeakMap & WeakSet

How do you iterate over a Map's entries?

Beginner

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.

Common follow-ups: Does destructuring work directly in the for...of loop header like this?