Map Vs WeakMap in Javascript
JavaScript provides various data structures to manage collections of key-value pairs, and two commonly used ones are Map and WeakMap. Both are used to associate values with keys, but they have distinct characteristics and use cases. In this blog, we will explore the differences between Map and WeakMap with examples to help you understand when to use each one.
This post was originally posted at https://agrawalsuneet.github.io/blogs/map-vs-weak-map-in-javascript/ and later reposted on Medium.
Map
A Map is a built-in JavaScript data structure introduced in ECMAScript 6 (ES6) that allows you to store key-value pairs where the keys can be of any type, including objects and primitive types. Map is especially useful when you need to maintain a mapping of keys to values, and it preserves the order of key insertion. Here’s an example of how to create and use a Map:
// Creating a Map
const myMap = new Map();
// Adding key-value pairs to the Map
const key1 = 'name';
const value1 = 'Alice';
myMap.set(key1, value1);
const key2 = { id: 1 };
const value2 = 'Bob';
myMap.set(key2, value2);
// Getting values from the Map
console.log(myMap.get(key1)); // Output: 'Alice'
console.log(myMap.get(key2)); // Output: 'Bob'
// Checking if a key exists in the Map
console.log(myMap.has(key1)); // Output: true
// Deleting a key-value pair from the Map
myMap.delete(key1);
// Iterating through the Map
for (const [key, value] of myMap) {
console.log(key, value);
}
WeakMap
A WeakMap is similar to a Map in that it stores key-value pairs, but it has a crucial difference: it can only use objects as keys and does not prevent those objects from being garbage collected when they are no longer in use.