JavaScript Maps
8 April 2025 | Category: JavaScript
A Map is a collection of key-value pairs, where keys can be of any data type — unlike objects, which only allow strings and symbols as keys.
✅ Key Features of Maps
- Stores key-value pairs.
- Keys can be any type (e.g., objects, functions, etc.).
- Maintains insertion order.
- Easily iterable using
for...of
.
🧱 Creating a Map
You can create a Map using the new Map()
constructor:
const myMap = new Map();
You can also initialize it with values:
const myMap = new Map([
["name", "John"],
["age", 30],
]);
➕ Adding Key-Value Pairs
Use .set()
to add a new pair:
myMap.set("country", "India");
myMap.set("age", 25); // updates the value if key exists
❓ Getting Values
Use .get()
to retrieve a value by its key:
console.log(myMap.get("name")); // John
🗑️ Deleting & Clearing
✅ delete(key)
myMap.delete("age");
✅ clear()
myMap.clear(); // removes all entries
🔍 Checking Keys
Use .has()
to check if a key exists:
console.log(myMap.has("country")); // true or false
🧮 Getting Size
Use .size
to get the number of entries in the map:
console.log(myMap.size);
🔁 Looping Through a Map
✅ Using for...of
for (let [key, value] of myMap) {
console.log(key + " = " + value);
}
✅ Using forEach()
myMap.forEach((value, key) => {
console.log(key + " => " + value);
});
🧪 Map with Different Key Types
const map = new Map();
const objKey = { id: 1 };
map.set(objKey, "Object as Key");
map.set(100, "Number as Key");
map.set(true, "Boolean as Key");
console.log(map.get(objKey)); // Object as Key
console.log(map.get(100)); // Number as Key
console.log(map.get(true)); // Boolean as Key
🧾 Summary of Map Methods
Method / Property | Description |
---|---|
set(key, value) | Adds or updates a key-value pair |
get(key) | Returns the value for a given key |
delete(key) | Removes a key-value pair |
has(key) | Checks if a key exists |
clear() | Removes all entries |
size | Returns the number of key-value pairs |
forEach() | Iterates over map entries |
📘 When to Use Maps?
- You need key-value storage with non-string keys.
- You care about the order of your data.
- You need performance for frequent additions/removals.