In JavaScript, maps are a data structure that allow you to store key-value pairs where both keys and values can be of any data type. Maps are similar to objects, but they have some differences and additional functionalities.
Basic Usage:
-
Creating a Map:
You can create a map using the
Map()
constructor:// Creating a new map let myMap = new Map();
-
Adding Entries:
To add key-value pairs to a map, you can use the
set()
method:// Adding entries to the map myMap.set('key1', 'value1'); myMap.set(2, 'value2'); myMap.set({ key: 'key3' }, 'value3');
-
Getting Values:
You can retrieve values using the
get()
method, passing in the key:// Retrieving values from the map console.log(myMap.get('key1')); // Output: value1 console.log(myMap.get(2)); // Output: value2
-
Checking Size:
To know the number of entries in a map, use the
size
property:// Checking the size of the map console.log(myMap.size); // Output: 3
-
Iterating through a Map:
You can iterate through a map using various methods like
forEach(), for...of
, or theentries()
method:// Iterating through the map myMap.forEach((value, key) => { console.log(`${key} => ${value}`); }); // Using for...of loop for (let [key, value] of myMap) { console.log(`${key} => ${value}`); }
- Key Types: In objects, keys are always converted to strings. In maps, keys can be of any data type (objects, functions, primitives, etc.).
- Order Preservation: Maps maintain the order of keys. This can be useful when iterating through them as they maintain insertion order.
-
Size Property:
Maps have a
size
property that provides the number of key-value pairs.
Methods:
Maps have various methods for managing and retrieving data, such as set(), get(), has(), delete(), clear(), forEach(), keys(), values(), and entries()
.
Example:
let myMap = new Map();
myMap.set('name', 'Alice');
myMap.set('age', 30);
myMap.set('dob', '1990-01-01');
console.log(myMap.get('name')); // Output: Alice
console.log(myMap.has('age')); // Output: true
myMap.delete('dob');
myMap.forEach((value, key) => {
console.log(`${key} => ${value}`);
});
Maps are versatile and useful for various scenarios where you need to store key-value pairs and maintain their order. They're handy for situations where you need more flexibility than what objects offer.