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...ofloop starts by callingMapobject's built-in[Symbol.iterator]()method (which is theMap.prototype.entries()method by default); - This returns a new iterator object which contains the
[key, value]pairs for each element in theMapobject (in insertion order); - Since the iterator objects implement the iterator protocol, the
for...ofloop knows it can call thenext()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']
}
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.