JavaScript Maps

A map in JavaScript is a collection that stores information in key and value pairs. When compared to a physical dictionary, the word would be the key, whilst the description would be the value. The keys are similar to values in a set in that they must be unique, with the value able to be duplicated if required.

The below example creates an empty map called 'people' and then adds three names as keys, along with their ages as values, using the 'set' method.

let people = new Map();

people.set("Bob Smith", 30);
people.set("Fred Bloggs", 43);
people.set("George Jones", 21);

It should be noted that if the key already exists in the map, then the 'set' method has the effect of updating the value for the key. The declaration and initialisation of a map can also be done in one statement.

let people = new Map([
   ["Bob Smith", 30],
   ["Fred Bloggs", 43],
   ["George Jones", 21]
]);

Similar to a set, a variation of a 'for' loop needs to be used to iterate through a map.

for ([key, value] of people.entries())
{

   document.write(key + " is " + value + " years old.<br />");

}

Here, the 'entries' method of the map is used to extract the key and value of each pair, which is then used to display a string that incorporates them both. The resulting output is shown below.

Bob Smith is 30 years old.
Fred Bloggs is 43 years old.
George Jones is 21 years old.

If it is necessary to return just one value based on a given key, then the 'get' method can be used.

document.write(people.get("Fred Bloggs"));

This will output 43. If the key of 'Fred Bloggs' didn't exist within the map, then an 'undefined' error would be returned. To mitigate this error a check could be made to see if the key exists within the map before trying to output its value by utilising the 'has' method.

if (people.has("Fred Bloggs"))
{
   document.write(people.get("Fred Bloggs"));
}

In order to remove a key and value pair from a map, the 'delete' method can be used, along with the key of the value that needs to be removed. Again, the 'has' method can be used to check that the key exists before trying to delete it so that any possible error is mitigated against.

if (people.has("Fred Bloggs"))
{
   people.delete("Fred Bloggs");
}

Finally, if it is required to find out how many key and value pairs are within the map, the 'size' property can be used.

document.write(people.size);