CodeZettaInterview Hub

JavaScript · OOP · Senior · Comparison

Compare ES private class fields (`#`) with WeakMap-based privacy patterns.

Short Interview Answer

`#fields` are language-enforced per-class privacy; WeakMaps associate hidden data with objects without exposing properties — useful for wrapping external objects.

Detailed Explanation

Private fields are only accessible inside the class body (including its methods); access from outside throws. They are not inherited as accessible names in subclasses (subclasses declare their own `#`). WeakMap privacy stores values keyed by the instance; if you don't export the map, data is effectively private and entries don't prevent GC. WeakMaps can decorate objects you don't control (e.g. DOM nodes). Trade-offs: `#` is clearer and faster in engines for typical class design; WeakMap is more flexible for libraries that attach metadata. Neither is a security boundary across realms.

Example

const secrets = new WeakMap();
class User {
  constructor(password) {
    secrets.set(this, password);
  }
  check(pw) {
    return secrets.get(this) === pw;
  }
}

Interview Tip

Discuss GC friendliness of WeakMap — senior detail.

Common Mistake

Using a module-level plain Map keyed by instance and leaking memory after instances die.

Did you know this answer?