Skip to content

JavaScript new Map with values

  • by

You can also initialize a Map with an array of key-value pairs using the new Map() constructor and passing in an array of arrays, where each inner array contains a key-value pair.

Or When you pass in an array of key-value pairs, the map will automatically create a new key-value pair for each item in the array.

JavaScript new Map with values example

Simple example code.

<!DOCTYPE html>
  <script >
    const myMap = new Map([
      ['key1', 'value1'],
      ['key2', 'value2'],
      ['key3', 'value3']




JavaScript new Map with values

You can also use the forEach() method to iterate over the key-value pairs in the Map, like this.

// Iterate over the key-value pairs in the Map
myMap.forEach(function(value, key) {
  console.log(key + ' = ' + value);

To access the values in the Map, we use the get() method, passing in the key as an argument. This returns the corresponding value for that key.

Do comment if you have any doubts or suggestions on this JS map topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *