JavaScript Map, Set, WeakMap & WeakSet Explained
JavaScript provides several built-in data structures for storing and managing collections of data.
The most commonly used ones are:
At first, they can look quite similar, but each one is designed for a different purpose.
For example:
const map = new Map();
const set = new Set();
const weakMap = new WeakMap();
const weakSet = new WeakSet();
So, when should you use each one?
In this article, we'll understand all four with simple examples and real-world use cases.
1. What Is a Map in JavaScript?
A Map is an object that holds key-value pairs where both the keys and the values can be any type of data. It is introduced in ES6.
Best for complex data where keys can be any type (objects, functions, etc.).
Unlike a normal Object, a Map can use any value as a key.
const users = new Map();
users.set(1, "Ali");
users.set(2, "Ahmed");
console.log(users.get(1));
Output:
You can use strings, numbers, objects, functions, and other values as Map keys.
Common Map Methods
map.set(key, value);
map.get(key);
map.has(key);
map.delete(key);
map.clear();
map.size;
Example:
const user = new Map();
user.set("name", "Ali");
user.set("role", "Developer");
console.log(user.get("name"));
console.log(user.has("role"));
console.log(user.size);
2. Iterating Over a Map
Maps are easy to iterate.
const users = new Map([
["name", "Ali"],
["age", 24],
["role", "Developer"]
]);
for (const [key, value] of users) {
console.log(key, value);
}
Output:
name Ali
age 24
role Developer
You can also use:
users.keys();
users.values();
users.entries();
When Should You Use Map?
Use Map when:
- You need key-value pairs.
- Keys can be different data types.
- You frequently add or remove entries.
- You need to preserve insertion order.
- You need built-in methods like
set(), get(), and has().
A common real-world example is caching:
const cache = new Map();
cache.set(userId, userData);
const user = cache.get(userId);
3. What Is a Set in JavaScript?
A Set is a built-in object introduced in ES6 that allows storing unique values (no duplicates) of any data type.
If you add the same value multiple times, it will only be stored once.
const numbers = new Set();
numbers.add(10);
numbers.add(20);
numbers.add(10);
console.log(numbers);
Output:
The duplicate 10 is automatically ignored.
Set Methods
set.add(value);
set.has(value);
set.delete(value);
set.clear();
set.size;
Example:
const skills = new Set();
skills.add("JavaScript");
skills.add("React");
skills.add("Node.js");
console.log(skills.has("React"));
console.log(skills.size);
Removing Duplicate Values with Set
One of the most useful applications of Set is removing duplicates from an array.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);
Output:
This is one of the simplest ways to remove duplicate primitive values from an array.
4. What Is a WeakMap in JavaScript?
A WeakMap is similar to a Map, but it has an important difference:
WeakMap keys must be objects or non-registered symbols.
For example:
const weakMap = new WeakMap();
const user = {
name: "Ali"
};
weakMap.set(user, "Developer");
console.log(weakMap.get(user));
Output:
You cannot use a normal string as a WeakMap key:
weakMap.set("user", "Ali");
That throws a TypeError.
Why Is It Called "Weak" Map?
The important concept is garbage collection.
Consider:
const weakMap = new WeakMap();
let user = {
name: "Ali"
};
weakMap.set(user, "Developer");
user = null;
After user no longer has another strong reference, the JavaScript engine can garbage-collect the object.
The WeakMap does not keep that object alive merely because it is used as a key.
This can be useful when associating extra information with objects without preventing those objects from being garbage-collected.
WeakMap Is Not Enumerable
Unlike Map, you cannot do:
or:
or:
for (const item of weakMap) {
}
This is intentional.
Because keys can disappear through garbage collection, the contents of a WeakMap are not designed to be enumerated.
Real-World WeakMap Example
WeakMap can be useful for storing metadata associated with objects.
const metadata = new WeakMap();
const user = {
name: "Ali"
};
metadata.set(user, {
lastLogin: "Today"
});
console.log(metadata.get(user));
The metadata is associated with the object without requiring you to modify the object itself.
5. What Is a WeakSet in JavaScript?
A WeakSet is similar to a Set, but it stores objects only.
const weakSet = new WeakSet();
const user = {
name: "Ali"
};
weakSet.add(user);
console.log(weakSet.has(user));
Output:
Primitive values cannot be added:
This causes a TypeError.
Why Use WeakSet in JavaScript?
WeakSet is useful when you only need to track whether an object has been seen or processed.
For example:
const processedUsers = new WeakSet();
const user = {
name: "Ali"
};
processedUsers.add(user);
if (processedUsers.has(user)) {
console.log("User already processed");
}
The object can still be garbage-collected when there are no other strong references to it.
Map vs Set vs WeakMap vs WeakSet
| Feature | Map | Set | WeakMap | WeakSet |
|---|
| Stores | Key-value pairs | Unique values | Key-value pairs | Objects |
| Keys | Any value | — | Objects / non-registered symbols | — |
| Values | Any value | Any value | Any value | Objects |
| Duplicates | Keys unique | Values unique | Keys unique | Objects unique |
| Iterable | Yes | Yes | No | No |
.size | Yes | Yes | No | No |
| Garbage-collection-friendly keys | No | N/A | Yes | Yes |
| Main use | Key-value data | Unique values | Object metadata | Object tracking |
Map vs WeakMap
The biggest difference is how their keys behave.
Map
const map = new Map();
let user = {
name: "Ali"
};
map.set(user, "Developer");
user = null;
The Map still has the key-value entry unless you explicitly remove it.
WeakMap
const weakMap = new WeakMap();
let user = {
name: "Ali"
};
weakMap.set(user, "Developer");
user = null;
The WeakMap does not prevent the object from being garbage-collected.
Set vs WeakSet
The same general idea applies here.
Set
A Set can store primitive values and objects.
const set = new Set();
set.add(10);
set.add("JavaScript");
set.add({ name: "Ali" });
WeakSet
A WeakSet only stores objects.
const weakSet = new WeakSet();
weakSet.add({
name: "Ali"
});
Which One Should You Use?
A simple way to remember:
Use Map
When you need:
Example:
Use Set
When you need:
Example:
without duplicates.
Use WeakMap
When you need:
and don't want the association to prevent garbage collection.
Use WeakSet
When you need:
without preventing those objects from being garbage-collected.
Common Mistakes
❌ Using WeakMap with strings
const weakMap = new WeakMap();
weakMap.set("user", "Ali");
WeakMap keys must be objects or non-registered symbols.
❌ Expecting WeakMap to have .size
console.log(weakMap.size);
WeakMap does not provide .size.
❌ Trying to iterate over WeakSet
for (const item of weakSet) {
console.log(item);
}
WeakSet is not iterable.
❌ Using Set when you need key-value relationships
If you need:
a Map is usually more appropriate than a Set.
Best Practices
-
Use Map for dynamic key-value collections.
-
Use Set when you need unique values.
-
Use WeakMap for object-associated metadata and similar object-keyed relationships where weak references are useful.
-
Use WeakSet when you need to track objects without keeping them alive.
-
Don't use Map or WeakMap just because they are newer than Objects.
Choose the data structure based on the problem you're solving.
Conclusion
Map, Set, WeakMap, and WeakSet are powerful collection types in modern JavaScript.
You don't need to choose one based on which is "better." Each one solves a different problem.
If you need key-value pairs, use Map.
If you need unique values, use Set.
If you need object-keyed data that should not prevent garbage collection, consider WeakMap.
If you need to track objects without keeping them alive, consider WeakSet.
Understanding these four collections will help you write cleaner JavaScript and is also extremely useful for JavaScript interviews.