Maps in JavaScript are an object type that allow you to store collections in key-value pairs. You can think of how a dictionary works in the sense that if you want to know the definition of a word (the value), you only need to locate the word itself (the key).

Creating a Map
Creating a map in JavaScript is the same as creating any object; using the new
keyword.
const map = new Map();
With your map defined, you can move on to adding elements to it.
Set
Adding an element to a map is done by setting an element. The idea here is that you're "setting" an entry into your map.
const map = new Map();
map.set("red", "apple");
map.set("blue", "blueberry");
map.set("green", "pear");
console.log(map);
0: {"red" => "apple"}
1: {"blue" => "blueberry"}
2: {"green" => "pear"}
Get
After you have populated a map with some elements, you can get them back by using the get
method and passing in the key.
const map = new Map();
map.set("red", "apple");
map.set("blue", "blueberry");
map.set("green", "pear");
const item = map.get("blue");
console.log(item);
blueberry
Great, we got back the value for the given key!
Size
Getting the size of a map is as simple as just using the size
property.
const map = new Map();
map.set("red", "apple");
map.set("blue", "blueberry");
map.set("green", "pear");
console.log(map.size);
3
Has
Instead of getting an element and then checking if it is null
or even if it exists at all, you can use the has
method to check if a map has a key and it returns true
if it exists and false
if not.
const map = new Map();
map.set("red", "apple");
map.set("blue", "blueberry");
map.set("green", "pear");
console.log(map.has("red"));
console.log(map.has("yellow"));
true
false
Delete
To get rid of an element in a map after it has been set, call the delete
method on it and pass in the key.
const map = new Map();
map.set("red", "apple");
map.set("blue", "blueberry");
map.set("green", "pear");
map.delete("blue");
console.log(map);
0: {"red" => "apple"}
1: {"green" => "pear"}
With blue
deleted, only red
and green
exist.
Clear
Clearing a map will delete all elements inside it, resetting it to a state as if it were a brand-new map.
const map = new Map();
map.set("red", "apple");
map.set("blue", "blueberry");
map.set("green", "pear");
map.clear();
console.log(map);
{}