Table of content:

Map is a JavaScript data structure you can use to store a collection of values, similar to Objects. It is a specialized data structure that can help you store and manipulate related values. In this tutorial, we will see how Map works in detail and when to use it.

The Map Object Explained

The Map object stores data in a key/value pair structure, just like an Object. The main differences between a regular object and a Map are:

  • Map can have any type of data as the key value
  • Map maintains the order of data added to the object

How to Create a Map Object

To create a Map object, you can call the Map() constructor as follows:

const myMap = new Map();

The code above creates a new empty Map object.

Map Object Methods and Properties

Map object has the following methods and properties:

  • set(key, value) – Adds a key/value pair to a Map
  • get(key) – Retrieves a value from a Map (returns undefined if key doesn't exist)
  • has(key) – Checks if a Map has a specific key
  • delete(key) – Removes a specific key from a Map
  • clear() – Removes all items from a Map
  • keys() – Returns all keys in a Map
  • values() – Returns all values in a Map
  • entries() – Returns all keys and values in a Map
  • size – Returns the number of items in Map

To insert data into the Map object, you can use the set() method:

const myMap = new Map();

myMap.set(1, 'Xuho');
myMap.set(2, 'Nguyen Hoa');
myMap.set('animal', 'Owl');

The code above creates a Map object with 3 entries as follows:

Map(3)
0: {1 => "Xuho"}
1: {2 => "Nguyen Hoa"}
2: {"animal" => "Owl"}

To retrieve a value from the Map object, you need to use the get() method and pass the key as its argument:

console.log(myMap.get(1)); // Xuho

console.log(myMap.get('animal')); // Owl

To see how many key/value pairs a Map has, you can access the size property:

myMap.size; // 3

To see if a certain key exists in a Map object, you can use the has() method. See the example below:

myMap.has(1); // true
myMap.has(10); // false

To remove a key/value pair from a Map object, you can use the delete() method and pass the key of the pair you want to remove as follows:

myMap.delete(1);

console.log(myMap);
// 0: {2 => "Nguyen Hoa"}
// 1: {"animal" => "Owl"}

If you want to remove all key/value pairs, you can use the clear() method instead:

myMap.clear();
console.log(myMap); // Map(0) {size: 0}

Other Ways to Create a Map Object

You can also create a Map object from an Array as follows:

const myMap = new Map([
  [1, 'Xuho'],
  [2, 'Nguyen Hoa'],
  ['animal', 'Owl'],
]);

When creating a Map from an Array, you need to create a two-dimensional array and specify two elements in each array.

The first element will be the key, the second element will be the value. Any extra value in the array will be ignored.

In the example below, the value 'Johnson' from the first array will be ignored by the Map() constructor:

const myMap = new Map([
  [1, 'Xuho', 'Hoanx'], // the value 'Hoanx' is ignored
  [2, 'Nguyen Hoa'],
  ['animal', 'Owl'],
]);

Because you can create a Map object from an array, you can also create one from an object. You need to transform the object into an array first using the Object.entries() method.

The following example shows how to use an object to create a Map:

const person = {
    'name': 'Xuho',
    'country': 'Vietnam',
}

const myMap = new Map(Object.entries(person));

console.log(myMap); // Map(2) { 'name' => 'Xuho', 'country' => 'Vietnam' }

Iterate Over Map Object Data

To iterate over a Map object data, you can use either the forEach() method or the for .. of loop:

const myMap = new Map([
  [1, 'Xuho'],
  [2, 'Nguyen Hoa'],
  ['animal', 'Owl'],
]);

// iterate using the forEach() method
myMap.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

// or using the for .. of loop

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

Both methods give the same output:

1: Xuho
2: Nguyen Hoa
animal: Owl

When to Use the Map Object

You can think of the Map object as an upgraded version of the regular Object. It can use any type of data as the key value, while an object can only use string values as keys.

Under the hood, the Map object performs better when you need to add and remove keys, so you might consider using it when your data changes frequently.

Also, the Map object has many useful methods for data manipulation, such as has() to see if the Map contains a specific key, keys() to get all keys defined in the Mapvalues to get all values, and entries() to get all key/value pairs.

But if you only want to create an object without further manipulation, then you don't need to use the Map object.

One example is when you send a network request using the fetch() method. You would create an object and convert it into a JSON string, so using a Map object won't give any benefit.