This post will discuss how to print all key-value pairs of a Map in JavaScript.

1. Map.prototype.forEach() function

The Map.prototype.forEach() function executes a callback function for each key-value pair in the map. The callback function can access the key and the value of the current pair and print them to the console using the console.log() function. For example, the following code prints all keys and values from a map:

Download  Run Code

Output:

a: 1
b: 2
c: 3

2. Using for…of loop

The for…of loop is used to loop over iterable objects, such as arrays, strings, maps, sets, etc. We can use it to iterate over the key-value pairs of the map and access the key and the value of each pair. Then we can print them to the console using the console.log() function. The following code illustrates this:

Download  Run Code

Output:

a: 1
b: 2
c: 3

3. Using Map.prototype.keys() and Map.prototype.values() functions

These functions return iterators that contain the keys and values of the map, respectively. We can use these functions to get arrays of keys and values using Array.from() or the spread operator (…). Then, we can use a regular for loop or a for…of loop to print them using console.log() function. Here’s an example of how we can achieve this:

Download  Run Code

Output:

a: 1
b: 2
c: 3

4. Using Array.prototype.map() function

The Array.prototype.map() function creates a new array populated with the results of calling a provided function on every element in an array. We can use the Array.from() function or the spread operator (…) to convert the map into an array of key-value pairs, then mapping over each pair using the map() function, and joining the key and value with a separator. Here’s an example of this approach:

Download  Run Code

That’s all about printing all key-value pairs of a Map in JavaScript.