02 / 03

Discuss how to declare public, private, static properties.

Difficulty: 3/10
class syntax, encapsulation, static members
prototype
  1. 1

    By default, all properties in ES6 classes are public, meaning they can be accessed from outside the class.

  2. 2

    Public properties can be read or modified from outside the class

  3. 3

    Private properties are restricted to the scope of the class and cannot be accessed directly from outside. As of ES2021, private properties can be created using the prefix.

  4. 4

    They can only be accessed or modified inside the class where they are defined. Attempting to access them directly outside the class results in an error.

  5. 5

    Static properties belong to the class itself, rather than instances of the class. They can be accessed directly on the class without creating an instance.

  6. 6

    They are shared among all instances and cannot be accessed via (unless from the class itself).

javascript

Scenario Questions

0-2 years experience

  1. 1How would you write a Counter class where the count can only be changed by increment() and decrement() methods, not from outside?
  2. 2What error do you get if you write `console.log(instance.#secret)` from outside the class, and why?

2-5 years experience

  1. 1You're building a User class where email must be set once in the constructor and never changed. Show me how you'd enforce that with modern JS syntax.
  2. 2A test suite shows a static `cache` Map on your Service class growing unbounded across test runs. Why is this happening and how do you fix it without breaking production?

5-8 years experience

  1. 1Design a plugin registry where each plugin class registers itself statically on load, but each plugin instance keeps its own private configuration state. Sketch the base class.
  2. 2Your team is migrating a 10-year-old codebase that uses `_private` naming convention for 'internal' properties. What's your strategy for adopting `#private` fields without a big-bang rewrite?

8+ years experience

  1. 1You own a shared component library used by 50+ teams. How do you decide when to use `#private` fields vs TypeScript `private` vs closure-based privacy? What's your governance model?
  2. 2A critical legacy module uses `Object.freeze` on instances for 'immutability' but still mutates internal `_state` objects. How do you refactor this to true encapsulation without breaking downstream consumers who reach into `_state`?

Follow-up Questions

  • What happens if a subclass tries to declare its own #sameName field?
  • How does static initialization order work when a static field references another static field?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.