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).
Use maps when you want to store key-value pairs.
Creating a Map
Creating a map in JavaScript is the same as creating any object; using the new keyword.
JAVASCRIPT
const map = newMap();
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. The syntax is:
Keep in mind that there can only be a single value assigned to each key. If you set red to cherry, the old value of apple is lost. Let's see what happens if you try to set red to cherry.
After you have populated a map with some elements, you can get them back by using the get method and passing in the key. The value that is returned is the value that was set for that key.
Getting the size of a map is as simple as just using the size property. The size of a map is the number of elements that are in the map. The following example shows how to get the size of a map:
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. The following example shows how to use the has method:
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. The following example shows how to use the delete method:
Clearing a map will delete all elements inside it, resetting it to a state as if it were a brand-new map. The following example shows how to use the clear method: