JavaScript provides several data structures for developers to use in their applications for storing and managing data. In this topic, you'll learn about the Map data structure. You might already have an idea of what a map looks like, as it is similar to the dictionary data structure in other programming languages. The Map object has key-value pairs, as well as many other properties or methods that you'll learn in this topic.
Map constructor
The Map object in JavaScript is a collection of key-value pairs where each key can be any data type, and the values can be of any type, including the objects and functions. That means any value, primitive or an object, can be used as a key and a value in a Map object.
You can create a Map object in JavaScript using a Map constructor, which is a built-in function in JavaScript. Let's see how you can create a Map object using the Map constructor in the syntax below:
const firstMap = new Map();This syntax explains how you can create a Map object in JS. One important parameter of the Map constructor is that it accepts an optional iterable parameter for populating the Map with initial key-value pairs. The iterable parameter should be an array of arrays, with two items in each subarray: the key and the value. Let's see an example:
const mapOfNames = new Map([
["key-1", "value-1"],
["key-2", "value-2"],
["key-3", "value-3"],
["key-4", "value-4"],
]);
console.log(mapOfNames);
// Output
Map(4) {
'key-1' => 'value-1',
'key-2' => 'value-2',
'key-3' => 'value-3',
'key-4' => 'value-4'
}As you can see, the Map object holds the key-value pairs and is arranged in the order of insertion of the keys. Each key is unique, which helps prevent redundancy in the data. You can also add key-value pairs using various methods available for the Map object, which we'll discuss in the next section.
A key in the Map may occur only once, which means every key is unique in a Map's collection.
Map methods
There are different methods available to manipulate or manage the data in the Map's collection. Let's discuss them one by one with examples.
The set method: Map.set(key, value)
Another way to add the key-value pairs in the Map object is by using the set() method. This method takes two arguments: a key and a value. If the key already exists in the Map, the set method will update the value associated with that key. Let's see an example:
// students.js
const students = new Map();
students.set(1, "John Mathews");
students.set("2", "Harry Rott");
students.set(3, "Kross Maiden");
students.set(1, "Riks Helly"); // updates the value for key 1
console.log(students);
// Output
Map(3) { 1 => 'Riks Helly', '2' => 'Harry Rott', 3 => 'Kross Maiden' }This is how you can add key-value pairs to a Map object and manipulate the data. Note that the value of the key 1 changes when we reassign the value with a new key and becomes "Riks Helly".
The get Method: Map.get(key)
Now that we have set the keys and values in the map, we need to be able to access the set values with the key. The get() method is used to get the value from the key. The elements of the respective key are extracted. Look at the example below:
// Code from students.js
console.log(students.get(1));
console.log(students.get("2"));
console.log(students.get(2));
// Output
Riks Helly
Harry Rott
undefinedYou can access the value associated with the given key. If the provided key to the get() method doesn't exist in the Map object, it will give undefined. In the example above, the key 2 doesn't exist, so it gives undefined but the key "2" exists, and it gives the output as "Harry Rott".
Other properties
Now you know how to create a Map object using the Map constructor method and how to set and get key-value pairs from a Map object. But there are also other properties and methods that you can use on the Map object;
Size: Map.size
Sometimes we need to know the Map object's size, which can be done with the size property. The size property returns the number of key-value pairs in the Map object. Let's take an example:
// Code from students.js
console.log(students.size); // 3As there are three elements in the students map object, the expected output will be 3.
Has: Map.has(key)
The has() method checks whether a specific key exists in the Map object. It returns a boolean value, that is, true if the key exists and false otherwise. Here is an example of it:
// Code from students.js
console.log(students.has("1")); // false
console.log(students.has(1)); // true
console.log(students.has(2)); // false
console.log(students.has("2")); // trueDelete: Map.delete(key)
The delete() method removes the key-value pair from the Map object. Here is an example:
// Code from students.js
students.delete(1);
console.log(students); // Map(2) { '2' => 'Harry Rott', 3 => 'Kross Maiden' }
students.delete("2");
console.log(students); // Map(1) { 3 => 'Kross Maiden' }Clear: Map.clear()
Now we know how to delete a specific key-value pair from a Map using the delete method. There is another method called the clear method, to remove an entire key-value pair from the Map.
// Code from students.js
students.clear();
console.log(students);Iterations
Now that we have created and populated our Map object with some key-value pairs, it's time to iterate over the Map. In this section, we'll discuss two methods for iterating over a map.
Using for...of loop
One simple way to iterate over a Map object is to use a for...of loop:
for (const [key, value] of students) {
console.log(`${key} = ${value}`);
}
// Output
1 = Riks Helly
2 = Harry Rott
3 = Kross MaidenUsing forEach method
Another way is to use the forEach() method:
// Code from students.js
students.forEach((value, key) => {
console.log(`${key} = ${value}`);
});
// Output
1 = Riks Helly
2 = Harry Rott
3 = Kross MaidenIn this method, forEach() is called on the Map object, and a callback function is passed as an argument. The callback function is called once for each entry in the map, and the key and value of each entry are passed as arguments to the function.
Maps vs objects
Maps and objects both store data in the form of key-value pairs, but there are some crucial differences between them.
Keys in a map can be any value, while keys in an object are limited to strings and symbols.
Maps maintain the order of their entries, while the order of keys in an object is not maintained.
Maps are often faster and more efficient than objects when working with large sets of data.
Conclusion
In this topic, you learned about the Map object in JavaScript, a powerful tool for creating collections of key-value pairs. It provides a variety of practical methods and properties you can use to manipulate and retrieve data in the map. You learned to use the Map constructor to create a new Map object, and then populate it with key-value pairs using the set() method. The get() method can then be used to retrieve the value associated with a particular key. There are several other properties like delete, clear, size, and more, which are beneficial while working with the Map object.