How to Iterate JavaScript Map Using for...of Loop?

Find out how to iterate a JavaScript Map with for..of

You can iterate over a JavaScript Map object using the for...of loop, like so:

const myMap = new Map();
myMap.set('US', 'en-US');
myMap.set('UK', 'en-GB');

for (const [key, value] of myMap) {
  console.log(`${key} => ${value}`); // 'US => en-US' 'UK => en-GB'
}

When you use the Map object with the for...of loop, the following happens:

  • The for...of loop starts by calling Map object's built-in [Symbol.iterator]() method (which is the Map.prototype.entries() method by default);
  • This returns a new iterator object which contains the [key, value] pairs for each element in the Map object (in insertion order);
  • Since the iterator objects implement the iterator protocol, the for...of loop knows it can call the next() method repeatedly (once each time through the loop) to get the next entry.

To demonstrate that the Map.prototype[Symbol.iterator]() method returns an iterable, you can call it directly on your Map object and use that in the for...of loop, for example, like so:

const myMap = new Map();
myMap.set('US', 'en-US');
myMap.set('UK', 'en-GB');

const iterator = myMap[Symbol.iterator]();

for (const item of iterator) {
  console.log(item); // ['US', 'en-US'] ['UK', 'en-GB']
}

Hope you found this post useful. It was published . Please show your love and support by sharing this post.