How to Use Maps in JavaScript

The Map utility in JavaScript is used to create keyed collections of data that can be updated using a set of built-in methods. They work in a similar way to objects and arrays, except maps allow keys to be anything, even functions.

 

In this article, we will go through how to use maps in JavaScript and explore the beneficial functionality that comes with converting a data set to a Map.

 

Create an Empty Map

To create an empty map, use the new Map() constructor. You will want to store the newly created map as a let (a local variable) or as a regular variable so it can be used in your code.

 

var things = new Map();

 

Map Methods and Properties

One of the most useful aspects of using Map is that it comes with a collection of methods that make updating data very easy and clean. Here are the available properties and methods in Map:

 

  • map.set(key, value) - add a new item to the map
  • map.get(key) - get an item from the map by its key
  • map.has(key) - check if a key exists in the map (returns true or false)
  • map.size() - get the number of items in the map
  • map.keys() - number of iterable for loop keys
  • map.values() - number of iterable for loop values
  • map.entries() - number of iterable for entires. [key, value]
  • map.delete(key) - delete an item from the map by its key
  • map.clear() - delete every item from the map

 

Creating a Map from an Array or Object

Let's assume we already have some data that we would like to create a map from. We will once again use the new Map() constructor, and pass the array variable inside the () (brackets).

 

var array = [
  [ 'dogs', 10 ],
  [ 'cats', 20 ],
  [ 'birds', 5 ],
  [ 'bears', 3 ]
];

var animals = new Map(array);

console.log(animals);
Map(4) {"dogs" => 10, "cats" => 20, "birds" => 5, "bears" => 3}

 

Note - the array that is to be converted into a map must be an array of arrays or an array of keyed objects.

 

Looping Through Maps Using For

To loop through a map we will use for of and one of the map for properties available for loops; keys, values and entries.

 

var array = [
  [ 'dogs', 10 ],
  [ 'cats', 20 ],
  [ 'birds', 5 ],
  [ 'bears', 3 ]
];

var animals = new Map(array);

// loop through keys
for (let animal of animals.keys()) {
  console.log(animal);
}
dogs
cats
birds
bears
// loop through the values
for (let animal of animals.values()) {
  console.log(animal);
}
10
20
5
3
// loop through [key, value]
for (let animal of animals.entries()) {
  console.log(animal);
}
["dogs", 10]
["cats", 20]
["birds", 5]
["bears", 3]

 

When using entries we will have the full [key, value] data to use. In the case of arrays, the individual data can be accessed using [] (square brackets) containing its index number.

 

// loop through [key, value]
for (let animal of animals.entries()) {
  console.log(animal[1]);
}
dogs
cats
birds
bears

 

Using Objects as Keys in Maps

One of the most useful aspects of maps is they can use objects as keys. In a scenario where you have objects and you need to keep another attribute of information about them in your program, a map will work perfectly.

 

var john = { name: "john" };

var userLastActive = new Map();

userLastActive.set(john, Date.now());

console.log(userLastActive.get(john));
1595079483134

 

In the above example, we are storing a map of when a user was last active using the user object as the key and Date.now() as the value. This is useful because we can get the last active date easily and get information about the user using the key should it be needed.

 

for (let user of userLastActive.entries()) {
  console.log(user[0].name + ' was last active ' + user[1]);
}
john was last active 1595079841717

 

Check if a Key Exists in a Map

To check if a key exists use the map.has() utility and pass in the name of the key as the first argument. It will return true or false.

 

var users = new Map();

users.set(1, "john")
  .set(2, "james")
  .set(3, "jeff")


var has = users.has(5);

console.log(has);
false

 

Get the Length of a Map

Use the map.size utility to get the number of items in the map. Works like the .length utility and will output a numerical value.

 

var users = new Map();

users.set(1, "john")
  .set(2, "james")
  .set(3, "jeff")


var size = users.size;

console.log(size);
3

 

Delete a Key from a Map

To delete an item from a map by its key name, use the map.delete() utility and pass in the name of the key as the first argument.

 

var users = new Map();

users.set(1, "john")
  .set(2, "james")
  .set(3, "jeff")


users.delete(2);

console.log(users);
Map(2) {1 => "john", 3 => "jeff"}

 

Empty a Map

To delete all items from the map use the map.clear() utility.

 

var users = new Map();

users.set(1, "john")
  .set(2, "james")
  .set(3, "jeff")


users.clear();

console.log(users);
Map(0) {}

 

Conclusion

You now know how to create maps in JavaScript and use all of the available utilities associated with a map.