JavaScript classes and private fields
Protect instance state with a private class field.
On this page
Functions, objects, and methods.
- Protect instance state with a private class field.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
class provides syntax for constructing objects with shared methods. A # field is private class state and can only be accessed from the declaring class's body.
A getter exposes a read-only public view without requiring callers to invoke a method. Each instance receives its own private field.
Code example
class Counter {
#value = 0;
increment() { this.#value += 1; }
get value() { return this.#value; }
}
const first = new Counter();
const second = new Counter();
first.increment();
first.increment();
console.log(first.value, second.value);
if (second.value !== 0) throw new Error("shared state");2 0
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
class Counter { #value = 0; increment() { this.#value += 1; } get value() { return this.#value; }}const first = new Counter();const second = new Counter();first.increment();first.increment();console.log(first.value, second.value);if (second.value !== 0) throw new Error("shared state");Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create the first private value. | first.#value = 0 | — | |
| Create a separate second value. | second.#value = 0 | — | |
| The two method calls update first from 0 to 1 to 2. | first.#value = 2, second.#value = 0 | — | |
| The getter returns each instance's value. | first.#value = 2, second.#value = 0 | — | |
| Print the public views. | first.#value = 2, second.#value = 0 | 2 0 |
Behind the scenes
How JavaScript processes this code
A JavaScript engine parses and runs the source. A function body runs when the function is called. console.log writes to the console.
Cost and common mistakes
O(1) work per increment and O(1) state per object.
- Accessing first.#value outside the class is a syntax error.
- Calling an extracted method without the correct receiver can lose this binding.
Try it yourself
Add a reset method and call it on first.
Reveal answer and reasoning
Inside the class, reset() can assign this.#value = 0. The output then becomes 0 0.