How to Use the Map Constructor in JavaScript?

Estimated read time 2 min read

The Map constructor in JavaScript allows you to create a collection of key-value pairs, where each key is unique. Here’s how you can use the Map constructor:

const map = new Map();

You can also initialize the map with an array of key-value pairs:

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ...
]);

Once you have created a Map object, you can add, retrieve, and remove key-value pairs using the following methods:

  • set(key, value): Adds a new key-value pair to the map.
  • get(key): Returns the value associated with the given key.
  • has(key): Returns a boolean indicating whether the map has a key-value pair with the given key.
  • delete(key): Removes the key-value pair with the given key.
  • clear(): Removes all key-value pairs from the map.

Here’s an example that demonstrates how to use these methods:

const map = new Map();

// Adding key-value pairs
map.set('key1', 'value1');
map.set('key2', 'value2');

// Retrieving values
console.log(map.get('key1')); // Output: value1

// Checking for keys
console.log(map.has('key1')); // Output: true

// Removing key-value pairs
map.delete('key1');
console.log(map.has('key1')); // Output: false

// Clearing the map
map.clear();
console.log(map.size); // Output: 0

Note that the Map constructor also has a size property that returns the number of key-value pairs in the map.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply