What are private class fields in JavaScript
· Category: JavaScript
Short answer
Private class fields are declared with a # prefix and are only accessible within the declaring class, providing hard privacy checked at the language level.
Steps
- Declare private fields:
javascript class Counter { #count = 0; increment() { this.#count++; } get count() { return this.#count; } } - Private methods:
javascript class Logger { #format(msg) { return `[${new Date().toISOString()}] ${msg}`; } log(msg) { console.log(this.#format(msg)); } } - Private static members:
javascript class Config { static #secret = "key"; static getSecret() { return this.#secret; } }
Tips
- Private fields are not accessible via reflection or proxies.
- Use private fields instead of underscore naming conventions for enforceable privacy.
Common issues
- Accessing a private field from outside the class throws a TypeError.
- Private fields must be declared at the top level of the class body, not created dynamically.