JavaScript Private Fields and Brand Checks
Quick answer
Private class elements use # names and class-defined access rules. They are not ordinary string-keyed properties.
How it works
Declare #balance = 0 inside a class and access it as this.#balance within the declaring class’s permitted lexical scope. A receiver without the private brand fails access with TypeError. #balance in obj tests private presence from the permitted scope; outside access to an undeclared private name is a syntax error. Object.keys and Reflect.ownKeys do not expose private elements.
class Counter { #n = 0; add() { this.#n++; } read() { return this.#n; } }const c = new Counter(); c.add(); c.add(); console.log(c.read(),Object.keys(c).length);Expected output in Node.js:
2 0Private state changes without becoming an ordinary own key.
class Token { #id = 1; static has(obj) { return #id in obj; } }console.log(Token.has(new Token()),Token.has({"#id":1}));Expected output in Node.js:
true falseA string property cannot manufacture the private brand.
Common mistakes
Private fields are language-level encapsulation, not a security boundary against all code with access to public methods.
Practice
Create two counters and expose only read and increment methods.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Private Fields and Brand Checks — Knowledge Check
Apply the taught concept and predict the output.
Does a string key named "#n" create the class private field #n?
Which API exposes private elements as ordinary keys?
What happens when permitted private access uses an unbranded receiver?
What is the exact console output in JavaScript Private Fields and Brand Checks example 1?
class Counter { #n = 0; add() { this.#n++; } read() { return this.#n; } }const c = new Counter(); c.add(); c.add(); console.log(c.read(),Object.keys(c).length);What is the exact console output in JavaScript Private Fields and Brand Checks example 2?
class Token { #id = 1; static has(obj) { return #id in obj; } }console.log(Token.has(new Token()),Token.has({"#id":1}));