The JavaScript Map class
ECMAScript 2015 introduced a Map class as part of the JavaScript API. We developed our Dictionary class based on the ES2015 Map class.
At its core, a Map is a collection of key-value pairs, similar to a dictionary or hash table in other programming languages. However, unlike plain JavaScript objects, a Map offers several key advantages as follows:
- The Map class allows keys of any data type, including objects, functions, or even other Map objects. In contrast, object keys are automatically converted to strings.
- The Map class maintains the order in which key-value pairs were inserted, making iteration predictable.
- We can easily get the number of entries using the size property, whereas with objects, we typically need to use
Object.keys(obj).length
. - The Map class natively supports iteration using
for...of
loops, making it more convenient to work with.
Now, let's take a look at the methods and features available in the native Map class:
set(key, value)
: adds...