What Is Map Data Structure in JS?

//

Scott Campbell

Map is a data structure in JavaScript that allows you to store key-value pairs. It is similar to an object, but with some key differences. In this tutorial, we will explore the Map data structure in JavaScript and understand how it can be used in various scenarios.

Creating a Map

To create a new Map object, you can use the Map() constructor. Here’s an example:

const map = new Map();

You can also pass an iterable as an argument to the constructor to initialize the map with key-value pairs:

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

Add and Retrieve Values from a Map

To add values to a map, you can use the .set() method. It takes two arguments: the key and the value.

// Add values to the map
map.set('key1', 'value1');
map.set('key2', 'value2');
map.set('key3', 'value3');

To retrieve values from a map, you can use the .get() method. It takes the key as an argument and returns the corresponding value.

// Retrieve values from the map
const value1 = map.get('key1');
const value2 = map.get('key2');
const value3 = map.get('key3');

Checking if a Key Exists in a Map

To check if a key exists in a map, you can use the .has() method. It takes the key as an argument and returns true if the key exists, or false otherwise.

// Check if a key exists in the map
const hasKey = map.has('key1');
// hasKey will be true

Iterating Over a Map

You can iterate over a map using various methods. One common method is to use the .forEach() method, which allows you to execute a function for each key-value pair in the map.

// Iterate over the map
map.forEach((value, key) => {
  console.log(`Key: ${key}, Value: ${value}`);
});

You can also use other methods like .keys(), .values(), or .entries() to get an iterator for keys, values, or key-value pairs respectively.

Removing Values from a Map

To remove a specific key-value pair from a map, you can use the .delete() method. It takes the key as an argument and removes the corresponding entry from the map.

// Remove a key-value pair from the map
map.delete('key1');

To clear all entries from a map, you can use the .clear() method.

// Clear all entries from the map
map.clear();

Conclusion

In this tutorial, we learned about the Map data structure in JavaScript. We explored how to create a map, add and retrieve values, check if a key exists, iterate over a map, and remove values.

Maps are incredibly useful when you need to store key-value pairs and perform operations based on keys. They provide efficient methods to manipulate data and offer flexibility in organizing information.