JavaScript Internals (521 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)
What are the differences between WeakMap and Map
The main difference is that references to key objects in Map are strong while references to key objects in WeakMap are weak. i.e, A key object in WeakMap can be garbage collected if there is no other reference to it.
Other differences are,
Mapcan store any key type whereasWeakMapcan store only collections of key objectsWeakMapdoes not have size property unlikeMapWeakMapdoes not have methods such as clear, keys, values, entries, forEach.WeakMapis not iterable.
Practical Code Example
javascript
// WeakMap vs Map:
// WeakMap keys MUST be objects and are weakly referenced (auto-GC):
const privateData = new WeakMap();
class User {
constructor(name, ssn) {
this.name = name;
privateData.set(this, { ssn }); // Private state hidden from inspection!
}
getSSN() {
return privateData.get(this).ssn;
}
}
const user = new User('Sarah', '123-45-6789');
console.log(user.name); // 'Sarah'
console.log(user.getSSN()); // '123-45-6789'