WeakMap is a special version of Map that holds keys “weakly”. This means that if the key object is no longer used anywhere else, the garbage collector can remove it along with its value from WeakMap. Keys can only be objects.
const weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'value');
console.log(weakMap.get(obj)); // 'value'
// Can't iterate!
// for (const [key, value] of weakMap) // Error!WeakMap is like a magical closet that cleans itself when things inside are no longer needed by anyone! If you put something in the closet, but nobody remembers that item anymore, the closet will throw it out by itself. This helps avoid memory leaks! 🧙
Main WeakMap features:
// Creating WeakMap
const privateData = new WeakMap();
// Objects as keys
const user1 = { name: 'John' };
const user2 = { name: 'Peter' };
// Adding data
privateData.set(user1, { password: '123' });
privateData.set(user2, { password: '456' });
// Getting data
console.log(privateData.get(user1)); // { password: '123' }
// Checking existence
console.log(privateData.has(user1)); // true
// Deletion
privateData.delete(user1);
console.log(privateData.has(user1)); // falselet obj = {};
const weakMap = new WeakMap();
weakMap.set(obj, 'data');
// When obj is no longer used
obj = null;
// Object and its data will be automatically removed
// by garbage collector (at some point)const weakMap = new WeakMap();
const key = {};
// set(key, value) — adds key-value pair
weakMap.set(key, 'value');
// get(key) — gets value by key
const value = weakMap.get(key);
// has(key) — checks key existence
const exists = weakMap.has(key);
// delete(key) — removes element by key
weakMap.delete(key);
// NO size property!
// NO clear() method!const weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'value');
// ❌ Error — can't iterate WeakMap
// for (const [key, value] of weakMap) // TypeError!
// ❌ Error — no keys(), values(), entries() methods
// weakMap.keys(); // TypeError!
// ❌ Error — no forEach
// weakMap.forEach(); // TypeError!const privateData = new WeakMap();
class User {
constructor(name) {
this.name = name;
// Private data not visible from outside
privateData.set(this, { password: 'secret' });
}
getPassword() {
return privateData.get(this).password;
}
}const cache = new WeakMap();
function processData(obj) {
if (cache.has(obj)) {
return cache.get(obj); // from cache
}
const result = heavyCalculation(obj);
cache.set(obj, result); // to cache
return result;
}
// When obj object is no longer needed,
// cache will automatically clear// ❌ Error — only objects as keys
const weakMap = new WeakMap();
// weakMap.set('string', 'value'); // TypeError!
// weakMap.set(123, 'value'); // TypeError!
// ✅ Correctly — only objects
const obj = {};
weakMap.set(obj, 'value'); // works// ❌ Error — thinking WeakMap is like Map
const weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'value');
// Can't iterate!
// weakMap.forEach((value, key) => {}); // Error!WeakMap is an excellent tool for storing data related to objects without risk of memory leaks! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪