A JavaScript Map is a collection that stores each of its elements as a key-value pair.
This data bang out is also referred to as an associative array or a dictionary.
The Map object remembers the original order of insertion, although you’ll typically access values by their key.
In this article, you’ll learn about ten JavaScript Map methods that you should master today.
This constructor accepts one parameter: an iterable object whose elements are key-value pairs.
Output:
If you don’t supply the parameter, JavaScript will create a new empty Map.
Here, the value stored against thekey2key isnewValue2, not the earliervalue2.
you could also create a Map object that holds key-value pairs using mixed data types.
This method accepts a key and a value, then adds a new element to the Map object.
The method then returns the new Map object with the added value.
If the key already exists in the Map, the new value will replace the existing value.
you could also use variables or constants as keys or values:
Theset()method supports chaining.
This method always returnsundefined.
This method accepts the key of the element to delete from the Map.
If the key exists, the method returnstrue.
Otherwise, it returnsfalse.
This method accepts the key of the element as a parameter to test for presence in the Map object.
This method returnstrueif the key exists.
Otherwise, it returnsfalse.
An element with key1966exists in the Map object, so the method returnedtrue.
But, since there’s no element with key1977in the Map object, the method returnedfalsefrom the second call.
Related:What Is JavaScript and How Does It Work?
Accessing the Value for a Specific Key
Theget()method returns a specific element from the Map object.
This method accepts the key of the element as a parameter.
If the key exists in the Map object, the method returns the value of the element.
Otherwise, it returnsundefined.
An element with key1966exists in the Map object, so the method returned the value of the element.
There’s no element with key1988in the Map object, so the method returnedundefined.
In this particular case, this iterator object is also iterable, so the for-of loop can be used.
Related:JavaScript Arrow Functions Can Make You a Better Developer
10.
The callback function takes two parameters: the key and value.
The Map data structure is widely used in many programming tasks.