Introduction
JavaScript offered only arrays and objects in the initial versions to store collections. Keyed collections are stored in objects, and for storing ordered collections, arrays were utilised.
But to solve complex real-life problems, these data structures weren't enough. That's why with ES6, JavaScript offers built-in classes for sets and maps that make the programming easier to maintain.
In this article, we'll be exploring the map and set data structures in JavaScript. So, let's get started!
What is a Map?
Before ES6, many JavaScript developers used to use the objects to map keys to their values. However, using an object as a map has limitations.
For example:
- There is no complete way to iterate over keys, and the keys() method converts fields to given strings, which leads to the collision of keys.
- There is also no simple way to add new keys and values to the object.
ES6 introduced new features like built-in classes, including a collection type called map, which tends to hold key-value pairs of any type. Unlike the previous generation object approach, the new Map object can even remember key insertion order.
In simple terms, we can conclude that a JavaScript Map is an associative collection of distinct keys and their corresponding values. Both keys and values can be any type, either primitive or object. This is a significant data structure with many practical uses.
Creation of Map:
let map = new Map([iterable]);
- The map () accepts an optional iterable object whose elements are key-value pairs.
Example of a Map:
'use strict';
const scores = new Map([['Shubham', 12], ['Vaishnavi', 13], ['Juhi', 10], ['Priyanka', 12]]);
scores.set('sohuard', 14);
console.log(scores.size);
Output:
5
Explanation
- The map scores that we have created above have been initialised with names and scores values. The initial data of the map may be iterable with the help of a pair of keys and values.
- We added a key and value to the map using the set() method with key "souhard".
- To figure out no of keys that are currently on the map, we used the size property.
Methods and Properties of Map
As an object, a Map is a collection of keyed data items. The main difference is that the map accepts any key.
The table below contains some of the methods of Maps in JavaScript.
Method | Description |
new map () | creates the map. |
map.set(key, value) | stores the value by the key. |
map.get(key) | returns the value by the key, undefined if the key doesn’t exist in the map. |
map.has(key) | returns true if the key exists, false otherwise. |
map.delete(key) | removes the value by the key. |
map.forEach(callback[, thisArg]) | invokes a callback for each key-value pair in the map in the insertion order. The optional thisArg parameter sets this value for each callback. |
map.clear() | removes everything from the map. |
map.size | returns the current element count. |
map.keys() | returns an iterable for keys. |
map.entries() | returns an iterable for entries [key, value]. |
map.values() | returns an iterable for values. |
Example: In the code below, we can extract the name and score for each key-value pair present in the map:
'use strict';
const scores = new Map([['Shubham', 12], ['Vaishnavi', 13], ['Juhi', 10], ['Priyanka', 12]]);
scores.set('Sohuard', 14);
console.log(scores.size);
for(const [name, score] of scores.entries())
{
console.log(`${name} : ${score}`);
}
Output:
5
Shubham : 12
Vaishnavi : 13
Juhi : 10
Priyanka : 12
Sohuard : 14
Initialisation of a Map:
We can pass an iterable object to the Map() constructor. Let’s understand with the help of an example.
Example:
let userRoles = new Map([
[shubham, 'admin'],
[Vaishnavi, 'editor'],
[Juhi, 'subscriber']
]);
Converting Keys or Values to Arrays:
When working with an array rather than an iterable object, we can use the spread operator. This will help us convert our keys or values into arrays. Let’s see with the help of an example:
Code Snippet: The below example creates an array of keys.
var keys = [...userRoles.keys()];
console.log(keys);
And the below piece of code will convert the values of elements to an array:
var roles = [...userRoles.values()];
console.log(roles);
This was all about maps in JavaScript. Let's get familiar with sets in JS now.