In JavaScript, a map is a collection of key-value pairs where each key is unique, and each key is associated with a value. Maps are also known as dictionaries, hashmaps, or associative arrays in other programming languages. They provide efficient ways to store, retrieve, and manipulate data based on keys.
Key Characteristics:
Key-Value Pairs:
- A map consists of a set of key-value pairs, where each key is unique within the map, and each key is associated with exactly one value.
Dynamic Size:
- Maps in JavaScript can grow or shrink dynamically, meaning you can add or remove key-value pairs as needed without specifying the size in advance.
Iterability:
- Maps are iterable, allowing you to loop through their key-value pairs using various iteration methods like
forEach
,for...of
, orentries
.
- Maps are iterable, allowing you to loop through their key-value pairs using various iteration methods like
Data Types:
- Keys and values in a map can be of any data type, including strings, numbers, objects, or even other maps.
Ordering:
- The order of key-value pairs in a map is based on the insertion order, meaning the keys maintain the order in which they were inserted.
Operations:
Set (Insertion/Update):
- Adds a new key-value pair to the map or updates the value of an existing key.
map.set(key, value);
Get (Retrieval):
- Retrieves the value associated with a specified key from the map.
let value = map.get(key);
Delete (Removal):
- Removes the key-value pair with the specified key from the map.
map.delete(key);
Has (Existence Check):
- Checks if the map contains a specific key.
if (map.has(key)) {
// Key exists in the map
}
Size:
- Returns the number of key-value pairs in the map.
let size = map.size;
Example Implementation:
// Creating a new map
let myMap = new Map();
// Adding key-value pairs
myMap.set("name", "John");
myMap.set("age", 30);
// Retrieving values
console.log(myMap.get("name"));
// Output: John
// Deleting a key-value pair
myMap.delete("age");
// Checking if a key exists
if (myMap.has("name")) {
console.log("Name exists in the map");
}
// Iterating over key-value pairs
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
Use Cases:
- Storing and retrieving data based on unique identifiers (keys).
- Implementing caches or memoization techniques.
- Managing configurations or settings with named keys.
- Handling complex data structures where relationships are defined by keys.