0% completed
Maps in JavaScript are a collection of keyed data items, just like an Object. However, Maps allow keys of any type, offering more flexibility and power in handling data than Objects. Maps maintain the insertion order of elements, which can be crucial for certain algorithms.
To create a Map, you can use the Map()
constructor, which optionally accepts an iterable (such as an array) of key-value pairs.
iterable
is an Array or any iterable object whose elements are key-value pairs (arrays with two elements).fruits
with three entries: apples, bananas, and oranges, with their respective quantities.Maps come with properties that help to inspect the collection:
Property | Description |
---|---|
size | Returns the number of key/value pairs in the Map object. |
Maps offer a variety of methods to manipulate the data:
Method | Description |
---|---|
set(key, value) | Adds or updates an element with a specified key and value to the Map object. |
get(key) | Returns the value associated with the key, or undefined if there is none. |
has(key) | Returns a boolean asserting whether a value has been associated with the key in the Map object or not. |
delete(key) | Removes any value associated with the key. |
clear() | Removes all key/value pairs from the Map object. |
entries() | Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order. |
keys() | Returns a new Iterator object that contains the keys for each element in the Map object in insertion order. |
values() | Returns a new Iterator object that contains the values for each element in the Map object in insertion order. |
forEach(callbackFn[, thisArg]) | Executes a provided function once per each key/value pair in the Map object, in insertion order. |
books
is created without any entries.set
method adds two books as keys with their authors as values.get
method retrieves the author of "1984".books
Map, returning true
because it was added previously.Comparing Maps to Objects:
Feature | Map | Object |
---|---|---|
Key Types | Any value type | Strings and Symbols |
Order of Elements | Maintains insertion order | No guaranteed order |
Size Property | Yes (size ) | No, must be computed manually |
Iteration | Directly iterable | Requires fetching keys or values |
Maps provide advantages over Objects when a collection of key-value pairs is needed, especially when complex keys or order are important.
.....
.....
.....