Skip to content

JavaScript new Map

  • by

You can use the new keyword along with the Map() constructor to create a new Map object in JavaScript. The Map object is a built-in data structure that allows you to store key-value pairs.

const myMap = new Map();

JavaScript new Map examples

Simple example code initializes the Map object with an array of arrays or another iterable object that contains key-value pairs.

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


    console.log(myMap);
    console.log(typeof(myMap));

  </script>
</body>
</html>

Output:

JavaScript new Map

You can add new key-value pairs to the Map object using the set() method:

myMap.set('key4', 'value4');

To Retrieve values from the Map object use the get() method:

const value = myMap.get('key1');
console.log(value); // output: 'value1'

Check if a key exists in the Map object using the has() method:

const hasKey = myMap.has('key1');
console.log(hasKey); // output: true

Iterate over the entries in the Map object using a for..of loop or the forEach() method:

for (const [key, value] of myMap) {
  console.log(`${key} = ${value}`);
}

myMap.forEach(function(value, key) {
  console.log(`${key} = ${value}`);
});

The Map the object also has other methods for working with its entries, such as delete(), clear(), and size.

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 *