JavaScript Map: Practical Guide
The Map
object in JavaScript is a built-in key-value data structure that allows you to store unique keys and their associated values. Unlike regular JavaScript objects ({}
), a Map
can have any type of key, including objects, functions, and primitive values.
1. Why Use Map
Instead of an Object?
Feature | Object {} | Map |
Key Types | Only strings and symbols | Any value (objects, functions, numbers, etc.) |
Order of Keys | Not guaranteed | Keys retain insertion order |
Performance | Slower for frequent additions/removals | Optimized for key-value operations |
Iteration | Requires Object.keys() , Object.values() | Direct iteration with .keys() , .values() , .entries() |
Size Property | No direct way (Object.keys(obj).length ) | map.size (built-in) |
2. Creating a Map
Basic Syntax
const myMap = new Map();
Adding Key-Value Pairs
Use .set(key, value)
to add entries.
const userRoles = new Map();
userRoles.set("Alice", "Admin");
userRoles.set("Bob", "Editor");
userRoles.set("Charlie", "Viewer");
console.log(userRoles);
// Map(3) { 'Alice' => 'Admin', 'Bob' => 'Editor', 'Charlie' => 'Viewer' }
Alternative: Initialize with an Array
const userRoles = new Map([
["Alice", "Admin"],
["Bob", "Editor"],
["Charlie", "Viewer"]
]);
console.log(userRoles.get("Alice")); // "Admin"
3. Working with Map
3.1. Retrieve Values
console.log(userRoles.get("Bob")); // "Editor"
If a key does not exist, it returns undefined
:
console.log(userRoles.get("David")); // undefined
3.2. Check If a Key Exists
console.log(userRoles.has("Alice")); // true
console.log(userRoles.has("David")); // false
3.3. Remove an Entry
userRoles.delete("Charlie");
console.log(userRoles.has("Charlie")); // false
3.4. Get the Size of a Map
console.log(userRoles.size); // 2
3.5. Clear All Entries
userRoles.clear();
console.log(userRoles.size); // 0
4. Iterating Over a Map
4.1. Using forEach()
userRoles.forEach((value, key) => {
console.log(`${key} => ${value}`);
});
4.2. Using for...of
with .entries()
for (let [key, value] of userRoles.entries()) {
console.log(`${key}: ${value}`);
}
4.3. Iterating Only Keys
for (let key of userRoles.keys()) {
console.log(key);
}
4.4. Iterating Only Values
for (let value of userRoles.values()) {
console.log(value);
}
5. Using Objects as Keys
Unlike regular objects, Map
allows objects as keys.
const user1 = { name: "Alice" };
const user2 = { name: "Bob" };
const userSettings = new Map();
userSettings.set(user1, { theme: "dark", fontSize: "14px" });
userSettings.set(user2, { theme: "light", fontSize: "16px" });
console.log(userSettings.get(user1)); // { theme: "dark", fontSize: "14px" }
- This is not possible with regular JavaScript objects.
6. Practical Use Cases
6.1. Counting Occurrences in an Array
const words = ["apple", "banana", "apple", "orange", "banana", "apple"];
const wordCount = new Map();
words.forEach(word => {
wordCount.set(word, (wordCount.get(word) || 0) + 1);
});
console.log(wordCount);
// Map(3) { 'apple' => 3, 'banana' => 2, 'orange' => 1 }
6.2. Storing User Sessions
const sessions = new Map();
function addSession(user, sessionId) {
sessions.set(user, sessionId);
}
function getSession(user) {
return sessions.get(user);
}
addSession("Alice", "abc123");
console.log(getSession("Alice")); // "abc123"
7. WeakMap vs Map
Key Differences
Feature | Map | WeakMap |
Key Types | Any value | Only objects |
Garbage Collection | No | Yes (keys are weakly held) |
Iterability | Yes (.keys() , .values() ) | No (not iterable) |
When to Use WeakMap
?
Use
WeakMap
when keys should be automatically removed when they are no longer needed.Ideal for caching or storing private data.
Example:
const weakMap = new WeakMap();
let obj = { name: "Alice" };
weakMap.set(obj, "some value");
console.log(weakMap.get(obj)); // "some value"
obj = null; // The object is garbage collected, and the entry is removed.
Conclusion
✅ Map
is a powerful alternative to objects when working with key-value pairs.
✅ It supports any data type as a key and maintains insertion order.
✅ Map
provides better performance for frequent additions and deletions.
✅ Use WeakMap
when you need automatic memory cleanup for objects.
Would you like more examples or a real-world application? 🚀