JavaScript Map

JavaScript Map

A JavaScript Map is a tool that allows you to store data in pairs of keys and values. Unlike objects, Maps can use any type of data as a key and keep the order of the items. In this blog, we will discuss what JavaScript Maps are, how to use them, and why they can sometimes be better than objects.

Table of Contents:

What is a JavaScript Map?

A JavaScript map is a way to store key-value pairs. The key and value can be of any data type, like a number, string, or object. It maintains the order of how you add the pairs and provides multiple ways to add, retrieve, check, and remove elements. It also has a built-in size property to get the number of elements in the map.

Why Use a Map in JavaScript?

You can use a map in JavaScript for several reasons:

  1. Any type of key: You can use objects, arrays, and even functions as a key. Unlike a regular object, which only allows strings or symbols as keys.
  2. Maintains the order: Map remembers the order in which you have added key-value pairs. So, you can loop through them in the same order.
  3. Built-in size property: You can easily find out how many key-value pairs are in a map by using the size property.
  4. Faster for changes: Maps are better when you need to add or remove items multiple times.
  5. Better for complex data: If you need to store and manage data with complex keys and values, then a map is a better choice than an object.

Creating a Map in JavaScript

You can create a map in JavaScript by using the Map() constructor. Let’s see how you can do it:

Syntax:

const myMap = new Map();
  • It will create an empty map. Now you can add keys and values to it.
Your path to becoming a web developer starts here
Master Web Development Today
quiz-icon

Creating a Map with Initial Values:

You can also create a map and add key-value pairs at the time of creation. You can do this by passing an array of arrays to the Map() constructor.

Example:

Javascript

Output:

Creating a Map with Initial Values

Methods and Properties of JavaScript Map

Here are some commonly used methods and properties of JavaScript maps:

1. set(key, value):

The set() method is used to add a new key-value pair to a map. If the key already exists in the map, then it will update the value of that key.

Syntax:

myMap.set('key', 'value');

2. get(key):

The get() method is used to retrieve the value using a specific key in the map. If the key doesn’t exist, then it will return undefined.

Syntax:

let key = myMap.get('key');

3. has(key):

The has() method is used to check if a specific key exists in the map or not. It will return true if the key exists and false if not.

Syntax:

myMap.has('key');

4. delete(key):

The delete() method is used to remove a key-value pair from the map depending on the given key. It will return true if the pair is successfully removed, and false if the pair does not exist.

Syntax:

myMap.delete('key');

5. clear(): 

The clear() method is used to delete all key-value pairs from the map and leaves it empty.

Syntax:

myMap.clear();

6. size:

The size property tells you the number of key-value pairs present in the map. It will give you the current count of entries in the map.

Syntax:

console.log(myMap.size);

7. forEach(callback):

The forEach() method is used to loop through all the key-value pairs in the map and apply the given callback function to every pair. The callback function takes the key, value, and Map itself as arguments.

Syntax:

myMap.forEach((value, key) => {
  console.log(key, value);
});

Example:

Let’s see an example by using all the above methods:

Javascript

Output:

Methods and Properties of JavaScript Map

Iterating Over a Map

You can iterate over a map by using the for…of loop along with keys(), values(), and entries() methods to get access to different parts of the Map. Let’s see how you can do it:

1. keys():

The keys() method returns an iterator object that gives you access to all the keys in the Map. You can use for…of to loop through the keys.

Syntax:

let keys = myMap.keys();
for (let key of keys) {
  console.log(key);
}

2. values():

The values() method returns an iterator object that gives you access to all the values in the Map. You can use for…of to loop through the values.

Syntax:

let values = myMap.values();
for (let value of values) {
  console.log(value);
}

3. entries():

The entries() method returns an iterator object that gives you access to all the key-value pairs in the Map as arrays of [key, value]. You can use for…of to loop through each pair.

Syntax:

let entries = myMap.entries();
for (let [key, value] of entries) {
  console.log(key, value);
}

Example:

Let’s see an example of iterating over the keys, values, and entries of a Map.

Javascript

Output:

Iterating Over a Map

Map vs Objects in JavaScript

Feature Map Object
Key Types You can use any type of key, like numbers, strings, or even objects. You can use only strings or symbols as keys. All other types will be converted into strings.
Order of Insertion It keeps the order of how you add things. It doesn’t guarantee the order. But in modern JavaScript, it keeps the order for string keys.
Performance It is faster when you need to add or remove multiple key-value pairs. It is slower for multiple changes.
Size Property It has a built-in size property to get the count of key-value pairs. It doesn’t have a size property. You have to use Object.keys(obj).length to count the properties.
Iteration You can easily loop through by using forEach() and for…of, or methods like keys() and values(). In this, you have to use for…in or methods like Object.keys().
Prototype Inheritance It doesn’t have a prototype. So there is no problem with extra properties. It can have extra properties because it inherits from the Object.prototype, which can create problems.

JavaScript Map with Complex Data Types

JavaScript Map can also store complex data types like objects, arrays, and functions as keys and values. Let’s see how you can work with complex data types in Maps:

1. Using Objects as Keys in a Map

In JavaScript, Maps allow you to use objects as keys, unlike a regular object that only allows strings or symbols. It is used when you need a key that is an object itself.

Example:

In this example, we have used an object “objKey” as a key and stored a value along with it. The key can be an object, and the Map will reference it without converting it into a string.

Javascript

Output:

Using Objects as Keys in a Map

2. Storing Arrays in a Map

You can use arrays as values in a Map that allows you to connect multiple items with a single key.

Example:

In this example, we stored an array of courses and connected them to the key “courses”. You can store any type of data, even arrays as values, in a Map.

Javascript

Output:

Storing Arrays in a Map

3. Storing Other Data Types in Maps

You can store any type of data, like numbers, strings, booleans, functions, and even other Maps or objects in a Map.

Example:

This example shows how you can store and retrieve different data types like numbers, booleans, and functions in a JavaScript Map.

Javascript

Output:

Storing Other Data Types in Maps

Common Use Cases for JavaScript Maps

Here are some of the common use cases for JavaScript Maps:

  1. Storing key-value pairs: Maps are used to store pairs of keys and values. Each key is unique, and it can be of any type, like a number, a string, or an object. It makes it easy to find values quickly by using keys.
  2. Counting occurrences: You can use a Map to find out how many times an item appears in the list. It is like counting how many times a word appears in a sentence.
  3. Storing object references as keys: You can use objects as keys in a Map. They are used when you need to track data about specific objects without converting them into strings.
  4. Memoization (caching results): Maps can be used to store the results of expensive function calls. If the same input is used again, then the Map will return the stored result. It saves time by avoiding repeated calculations.
  5. Iterating in insertion order: Maps keep the order of the keys the same as they are inserted. It means when you are looping through the Map, the keys will appear in the same order in which you added them.

When to Choose a Map?

  1. Non-string keys: If you need to use things like numbers, objects, or functions as keys, then Map is a good choice because regular objects can only use strings as keys.
  2. Frequent additions/removals: You should use Maps when you need to add or remove key-value pairs very frequently because Maps can handle these operations much better than regular objects.
  3. Ordered data: If the order of the items in which they are added is important to you, then Maps are good because they remember the order of insertion.
  4. Predictable iteration: Maps guarantee the order when you loop through them. But with objects, this can be unpredictable sometimes, especially when you are using numerical keys.
  5. Dynamic or unknown keys: If you don’t know the keys before writing the program, or they will be changed during the program, then Maps are good to work with. They are easy and flexible to use.

Common Problems with JavaScript Maps

  1. Don’t complicate simple cases: If you are only working with basic string keys and don’t need any extra features of a Map, then a regular object will work better and faster.
  2. Performance issues for small data sets: Maps are good for large and complicated datasets, but for smaller datasets, objects might work better because they have less overhead.
  3. Don’t treat maps like objects: Maps store key-value pairs in order, while objects don’t do that sometimes, and they cannot store non-string keys, while Maps can.
  4. Checking keys before accessing values: If you want to get a value from a Map, first you should check if the key exists in the Map or not to avoid getting undefined.
  5. Serialization problems: If you need to convert a Map into a format like JSON to save or send it, then remember you can’t do it directly. You have to convert it into an array or some other format first.
  6. Don’t mix up with sets: A Set is used to store unique values, and a Map is used to store key-value pairs, so don’t get confused between them.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

So far in this blog, we have learned what JavaScript Maps are, how to use them, and why sometimes they can be better than objects. A JavaScript map is a way to store key-value pairs. The key and value can be of any data type, like a number, string, or object. Map remembers the order in which you have added key-value pairs. So, you can loop through them in the same order.

JavaScript Map – FAQs

Q1. Can I have duplicate keys in a Map?

No, you can’t have duplicate keys in a Map. Each key must be unique. If you try to insert a new key-value pair with a key that already exists in the Map, it will overwrite the previous value that is connected with that key.

Q2. What happens if I try to access a non-existent key in a Map?

If you try to access a key that doesn’t exist, then it will return undefined instead of giving an error. You can use the .has() method to check if a key exists or not before accessing its value.

Q3. What are the main methods of a Map?

Some of the most commonly used methods of a Map are:
.set(key, value): It adds or updates a key-value pair.
.get(key): It retrieves the value associated with a given key.
.has(key): It checks if a key exists in the Map or not.
.delete(key): It removes a key-value pair from the Map using the key.
.clear(): It clears all key-value pairs from the Map.
.size: It returns the number of key-value pairs in the Map.

Q4. Can Maps be nested?

Yes, you can store a Map inside another Map, or you can even store Maps as values in a Map. This allows you to create nested data structures.

Q5. Can a Map have non-iterable keys?

Yes, Map can use non-iterable keys like null and undefined.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner