AceDevHub
Advanced JavaScript Interview QuestionsAdvancedComparison

JavaScript · Question 80

How do JavaScript private class fields differ from underscore conventions and WeakMap-based privacy?

Direct answer

Private class fields use language-enforced private names that can only be accessed where that private name is lexically declared; underscore properties are only conventions, while WeakMaps can provide externally associated private state with different composition trade-offs.

A field such as #balance is not a normal string property named "#balance". Access is syntactically restricted to code that has access to that private name, and arbitrary reflection does not expose it as a normal own key. This is stronger than naming a public property _balance.

Before private fields, a WeakMap keyed by instances was a common privacy pattern. It still has useful properties: state can live outside the object’s visible property set and the weak key does not by itself keep the instance alive. But it requires an external map and lookup rather than class-private syntax.

  • Use #private fields when the state naturally belongs to a class and should be enforced by the language.
  • Use WeakMap-associated metadata when privacy or metadata needs to be attached externally across objects without adding visible properties.
  • Private fields also perform a brand check: attempting access on an object that does not carry the declared private field throws rather than returning undefined.