Maps in JavaScript

Maps are JavaScript’s built-in associative data type (sometimes called hashes or dicts in other languages).

To create an empty map, use the Map constructor:

let m = new Map();

Set key/value pairs using typical set method:

m.set("k1", 7);
m.set("k2", 13);

Printing a map using console.log will show all its key/value pairs:

console.log("map:", m);

Get a value for a key with the get method:

let v1 = m.get("k1");
console.log("v1:", v1);

If the key doesn’t exist, undefined is returned:

let v3 = m.get("k3");
console.log("v3:", v3);

The size property returns the number of key/value pairs in a Map:

console.log("len:", m.size);

The delete method removes key/value pairs from a map:

m.delete("k2");
console.log("map:", m);

To remove all key/value pairs from a map, use the clear method:

m.clear();
console.log("map:", m);

The has method indicates if a key is present in the map:

let prs = m.has("k2");
console.log("prs:", prs);

You can also declare and initialize a new map in the same line with this syntax:

let n = new Map([["foo", 1], ["bar", 2]]);
console.log("map:", n);

JavaScript does not have a built-in maps package for utility functions. Instead, commonly used methods like size, clear, and others are already available on the Map object. For instance, to check if two maps are equal, you’d need to create a custom comparison function.

Note that maps appear in the form Map { key1 => value1, key2 => value2 } when printed with console.log.

$ node maps.js
map: Map { 'k1' => 7, 'k2' => 13 }
v1: 7
v3: undefined
len: 2
map: Map { 'k1' => 7 }
map: Map {}
prs: false
map: Map { 'foo' => 1, 'bar' => 2 }