How to iterate a Map in Javascript - Map Part 2

js

If you missed reading the first article in which we discussed how to do basic operations over a Map, you can read it here.

In this article, we will learn how to iterate over a Map using different methods available. So, let’s dive in and learn how to loop over a Map.

Iterating a Map

For iterating over a Map, we can use the following javascript constructs:

  • for..of
  • forEach()

Let's create a Map first to loop over from the knowledge gained in our previous article.

1
2
3
4
5
let map = new Map()

map.set("one", "first element");
map.set("two", "second element");
map.set(3, "third element");

Iterating map with for..of

We can use for..of to iterate a Map in Javascript.

1
2
3
4
5
6
7
8
for (let [key, value] of map) {
console.log(key + " = " + value);
}

//output
// one = first element
// two = second element
// 3 = third element

Map also provides these three methods, which comes in handy while iterating over a Map.

  • map.keys() - Returns an iterable for keys
  • map.values() - Returns an iterable for values
  • map.entries() - Returns an iterable of key,value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
for (let key of map.keys()) {
	console.log(key);
}

// output
// one
// two
// 3

for (let value of map.values()){
	console.log(value);
}

// output
// first element
// second element
// third element

for (let [key, value] of  map.entries()) {
	console.log(key + " = " + value)
}

//output
// one = first element
// two = second element
// 3 = third element

Iterating Map with forEach()

We can also iterate through a Map using forEach().

1
2
3
4
5
6
7
8
map.forEach(function(value, key) {
	console.log(key + " = " + value);
})

//output
// one = first element
// two = second element
// 3 = third element

Map preserves the order in which values are inserted. So, while iterating over a Map, elements will be in the same order in which they are inserted.

Summary

  • To iterate over a Map, we can use for..of and forEach() loop constructs.
  • Map provides three methods that return iterable: map.keys(), map.values() and map.entries().
  • Iteration over Maps is always in insertion order.

If you liked this article, please upvote and recommend it to show your support. Feel free to ask any questions in the comments below.


We publish articles on web development and technology frequently. Consider subscribing to our newsletter or follow us on our social channels (twitter, Facebook, LinkedIn).

Share and support us

Share on social media and help us reach more people