JavaScript Map
JavaScript provides four specialized collection types beyond plain objects and arrays: Map, Set, WeakMap, and WeakSet. Each serves a specific purpose and solves real problems that plain objects and arrays handle less efficiently.
Map
A Map is a collection of key-value pairs — similar to a plain object, but with important differences. In a Map, keys can be of any type (not just strings), and the insertion order of entries is preserved.
Creating and Using a Map
let userMap = new Map();
// Set key-value pairs
userMap.set("name", "Ananya");
userMap.set("age", 28);
userMap.set("city", "Bangalore");
// Get values
console.log(userMap.get("name")); // Ananya
console.log(userMap.get("age")); // 28
// Check if a key exists
console.log(userMap.has("city")); // true
console.log(userMap.has("email")); // false
// Get total number of entries
console.log(userMap.size); // 3Map Keys Can Be Any Type
let map = new Map();
let objKey = { id: 1 };
let fnKey = function() {};
map.set(objKey, "Object as key");
map.set(fnKey, "Function as key");
map.set(1, "Number as key");
map.set(true, "Boolean as key");
console.log(map.get(objKey)); // Object as key
console.log(map.get(1)); // Number as keyIterating Over a Map
let scores = new Map([
["Rahul", 88],
["Priya", 95],
["Amit", 76]
]);
// Iterate with for...of
for (let [name, score] of scores) {
console.log(`${name}: ${score}`);
}
// Using forEach
scores.forEach((score, name) => {
console.log(`${name} scored ${score}`);
});
// Get all keys
console.log([...scores.keys()]); // ["Rahul", "Priya", "Amit"]
// Get all values
console.log([...scores.values()]); // [88, 95, 76]
// Get all entries
console.log([...scores.entries()]); // [["Rahul", 88], ["Priya", 95], ...]Deleting and Clearing Map Entries
let map = new Map([["a", 1], ["b", 2], ["c", 3]]);
map.delete("b");
console.log(map.size); // 2
map.clear();
console.log(map.size); // 0Map vs Object — When to Use Which
| Feature | Object | Map |
|---|---|---|
| Key types | String / Symbol only | Any type |
| Order preserved | Mostly yes (ES2015+) | Always yes |
| Size property | No (manual count) | map.size |
| Iteration | for...in (includes prototype) | for...of (only own entries) |
| Best use | Structured data, JSON | Flexible key-value lookup |
Set
A Set is a collection of unique values. Duplicate values are automatically ignored. Sets are iterable and maintain insertion order.
Creating and Using a Set
let fruits = new Set(["Apple", "Banana", "Mango", "Apple", "Banana"]);
console.log(fruits); // Set { "Apple", "Banana", "Mango" }
console.log(fruits.size); // 3 — duplicates removed
fruits.add("Orange");
fruits.add("Mango"); // Duplicate — ignored
console.log(fruits.has("Orange")); // true
console.log(fruits.size); // 4Removing Items from a Set
let tags = new Set(["js", "html", "css", "js"]);
tags.delete("html");
console.log(tags); // Set { "js", "css" }
tags.clear();
console.log(tags.size); // 0Iterating Over a Set
let colors = new Set(["Red", "Green", "Blue"]);
for (let color of colors) {
console.log(color);
}
// Spread into array
let colorArray = [...colors];
console.log(colorArray); // ["Red", "Green", "Blue"]Practical Use — Remove Duplicates from Array
let numbers = [1, 2, 2, 3, 3, 3, 4, 5, 5];
let unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]Set Operations (Union, Intersection, Difference)
let setA = new Set([1, 2, 3, 4]);
let setB = new Set([3, 4, 5, 6]);
// Union — all elements from both
let union = new Set([...setA, ...setB]);
console.log([...union]); // [1, 2, 3, 4, 5, 6]
// Intersection — elements in both
let intersection = new Set([...setA].filter(x => setB.has(x)));
console.log([...intersection]); // [3, 4]
// Difference — elements in A but not in B
let difference = new Set([...setA].filter(x => !setB.has(x)));
console.log([...difference]); // [1, 2]WeakMap
A WeakMap is like a Map, but with two key differences:
- Keys must be objects (not primitives)
- Keys are held weakly — if an object used as a key is garbage collected, the entry is automatically removed
WeakMaps are not iterable and have no size property. They are primarily used to store private data associated with objects.
let weakMap = new WeakMap();
let user = { name: "Kiran" };
weakMap.set(user, { lastLogin: "2026-03-01" });
console.log(weakMap.get(user)); // { lastLogin: "2026-03-01" }
console.log(weakMap.has(user)); // true
user = null; // Object is eligible for garbage collection
// WeakMap entry is also automatically cleared — no memory leakPractical WeakMap Use — Private Data per Instance
const privateData = new WeakMap();
class User {
constructor(name, password) {
privateData.set(this, { password });
this.name = name;
}
checkPassword(input) {
return privateData.get(this).password === input;
}
}
let u = new User("admin", "pass123");
console.log(u.checkPassword("pass123")); // true
console.log(u.checkPassword("wrong")); // false
// No way to access password directly from outsideWeakSet
A WeakSet is like a Set, but only stores objects and holds them weakly. When an object is no longer referenced elsewhere, it is automatically removed from the WeakSet.
WeakSets are not iterable and have no size property.
let weakSet = new WeakSet();
let obj1 = { task: "Send email" };
let obj2 = { task: "Review PR" };
weakSet.add(obj1);
weakSet.add(obj2);
console.log(weakSet.has(obj1)); // true
obj1 = null; // Automatically removed from weakSet when garbage collected
console.log(weakSet.has(obj1)); // falsePractical WeakSet Use — Track Processed Objects
let processed = new WeakSet();
function processRequest(req) {
if (processed.has(req)) {
console.log("Already processed:", req.id);
return;
}
processed.add(req);
console.log("Processing request:", req.id);
}
let req1 = { id: 101, data: "abc" };
processRequest(req1); // Processing request: 101
processRequest(req1); // Already processed: 101Summary Table
| Collection | Key Type | Unique Values | Iterable | Memory Leak Safe |
|---|---|---|---|---|
| Map | Any | No | Yes | No (strong refs) |
| Set | Any (values) | Yes | Yes | No (strong refs) |
| WeakMap | Objects only | No | No | Yes (weak refs) |
| WeakSet | Objects only | Yes | No | Yes (weak refs) |
Key Points to Remember
- A
Mapstores key-value pairs where keys can be any type, not just strings - A
Setstores unique values — duplicates are automatically rejected - Use a Set to quickly remove duplicates from an array with
[...new Set(array)] WeakMapandWeakSethold object references weakly — they do not prevent garbage collectionWeakMapis ideal for storing private data associated with class instancesWeakSetis ideal for tracking which objects have been processed- WeakMap and WeakSet are not iterable and have no
sizeproperty
