Skip to the workspace
Pebellslearn by building
Classes  ›  Lesson

Private Fields

Classes 12 min

javascript / Private Fields

Explore each scene at your own pace.

01 · Private Fields

Private Fields

Private Fields

Private fields declared with # are accessible only within the class body that declares them. They are not ordinary string-keyed properties.

Keep an implementation detail behind methods that control how it changes.

See the mechanism

Walk through the modelPrivate FieldsAuthored snapshots of the example; use Run below to test the code.
private #count0
The class controls access to this field.
1 of 3

Follow one example

javascript

count is a public getter that deliberately exposes a read-only view. The private #count slot is different from an ordinary property whose string key is "#count", so the bracket lookup returns undefined. Writing counter.#count outside the class is a syntax error. Privacy controls access, not automatic validation or encryption.

Predict, change and check

Predict: Will adding counter["#count"] = 99 change the private counter?

Test your explanation: Try that ordinary property assignment and compare counter.count. Add a reset method only if the class should explicitly support resetting.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Private names are enforced, not naming conventions

A #private field is a language-enforced private element declared in a class. It differs from a property whose string name starts with an underscore. Access requires an object that has the appropriate private element; even a method with private access can fail if called with an incompatible receiver.

A private field does not make the entire instance deeply immutable or automatically release retained resources. Public methods still define the object's valid behavior and lifetime. Keep an invariant in the private state, expose a small operation, and test invalid transitions rather than trying to read private state through ordinary bracket syntax.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.