InterviewHubPRO
Section Overview
Q212

Question 212 of 521

Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

41%
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,

  1. Map can store any key type whereas WeakMap can store only collections of key objects
  2. WeakMap does not have size property unlike Map
  3. WeakMap does not have methods such as clear, keys, values, entries, forEach.
  4. WeakMap is 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'