Mastering Map, WeakMap, Set, and WeakSet in JavaScript
A concise guide to JavaScript's powerful collection data structures.
JavaScript's Map, WeakMap, Set, and WeakSet are powerful data structures introduced in ES6. They enhance functionality over traditional objects and arrays, especially in terms of performance, memory management, and specific use cases. This guide explores their features, use cases, and differences to help you master them.
1. Map
1.1 Definition
A Map is a collection of key-value pairs where keys can be of any data type. Unlike regular objects, a Map allows non-string keys and guarantees insertion order.
1.2 Features
Keys of any type: Supports objects, functions, and primitive types.
Ordered: Maintains the order of key-value pair insertion.
Size property: Provides the total number of entries.
Iterable: Supports iteration methods like
forEach
andfor...of
.Performance: Faster for frequent operations, especially with non-string keys.
1.3 Common Methods
const map = new Map();
// Add key-value pairs
map.set('name', 'Alice'); // string key
map.set(1, 'Number'); // numeric key
map.set(true, 'Boolean'); // boolean key
// Get value by key
console.log(map.get('name')); // Alice
console.log(map.get('age')); // undefined
// Check key existence
console.log(map.has(1)); // true
// Delete by key
map.delete('name'); // removes 'name' key
// Clear all entries
map.clear();
// Get size
console.log(map.size); // 0
1.4 Iteration
map.set('color', 'red');
map.set('shape', 'circle');
map.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
// Using entries()
for (let [key, value] of map.entries()) {
console.log(key, value);
}
2. WeakMap
2.1 Definition
A WeakMap is similar to a Map but with the following distinctions:
Keys must be objects.
Keys are weak references, meaning they do not prevent garbage collection.
2.2 Features
Memory management: Keys are automatically removed when no longer referenced.
No iteration: Not iterable due to weak references.
Size property not available: You cannot determine the size of a WeakMap.
2.3 Common Methods
let weakMap = new WeakMap();
let obj = {};
weakMap.set(obj, 'value'); // Set a key-value pair
console.log(weakMap.get(obj)); // 'value'
console.log(weakMap.has(obj)); // true
weakMap.delete(obj); // Removes the key
3. Set
3.1 Definition
A Set is a collection of unique values, maintaining the order of insertion.
3.2 Features
Unique values: Automatically removes duplicates.
Ordered: Maintains insertion order.
Size property: Provides the total number of elements.
Iterable: Supports iteration methods.
3.3 Common Methods
let set = new Set([1, 2, 2, 3]);
// Add elements
set.add(4);
// Check for existence
console.log(set.has(3)); // true
// Remove an element
set.delete(2);
// Clear all elements
set.clear();
// Get size
console.log(set.size); // 0
3.4 Deduplication Example
let arr = [1, 2, 3, 3, 4, 4];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4]
4. WeakSet
4.1 Definition
A WeakSet is a collection of objects where references are weak, allowing automatic garbage collection.
4.2 Features
Only objects: Elements must be objects.
Weak references: Objects are removed if no other references exist.
Not iterable: Does not support iteration.
Size property not available: You cannot determine the size.
4.3 Common Methods
let weakSet = new WeakSet();
let obj1 = {};
weakSet.add(obj1); // Add an object
console.log(weakSet.has(obj1)); // true
weakSet.delete(obj1); // Removes the object
5. Comparison
Type of Keys:
Map: Any type
WeakMap: Objects only
Set: N/A
WeakSet: Objects only
Value Types:
Map: Any type
WeakMap: Any type
Set: Any type
WeakSet: Objects only
Memory Management:
Map: Persistent
WeakMap: Keys are garbage-collected
Set: Persistent
WeakSet: Elements are garbage-collected
Size Property:
Map: Yes
WeakMap: No
Set: Yes
WeakSet: No
Iteration Support:
Map: Yes
WeakMap: No
Set: Yes
WeakSet: No
6. Use Cases
Map:
Key-value storage with non-string keys.
Caching and fast lookups.
WeakMap:
Associating metadata with objects.
Avoiding memory leaks in DOM-related operations.
Set:
Removing duplicates in arrays.
Performing set operations like union, intersection, and difference.
WeakSet:
Tracking objects without preventing garbage collection.
Managing object references for DOM elements or resources.
Mastering these data structures will enhance your ability to write efficient, clean, and memory-safe JavaScript code.