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:
Set key/value pairs using typical set
method:
Printing a map using console.log
will show all its key/value pairs:
Get a value for a key with the get
method:
If the key doesn’t exist, undefined
is returned:
The size
property returns the number of key/value pairs in a Map:
The delete
method removes key/value pairs from a map:
To remove all key/value pairs from a map, use the clear
method:
The has
method indicates if a key is present in the map:
You can also declare and initialize a new map in the same line with this syntax:
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
.