Private Fields and Methods in JavaScript Classes
JavaScript classes support truly private fields and methods using names that begin with #. They can be accessed only from code inside the class body that declares them.
Private Fields
class Person {
#name;
constructor(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}Trying to access person.#name outside the class is a syntax error.
Private Methods
class Counter {
#count = 0;
#increment() {
this.#count++;
}
increment() {
this.#increment();
return this.#count;
}
}Private methods are useful for internal implementation details that should not become part of the public API.
Encapsulation, Not Secret Storage
Private fields prevent ordinary external access through the object interface, but they should not be treated as a cryptographic security boundary. Do not store plaintext passwords or other secrets merely because the field is private.
For example, application passwords should be verified using secure password hashing on a trusted server rather than held in a browser class field.
Inheritance
A subclass cannot directly access a parent’s private field:
class Base {
#value = 1;
}
class Child extends Base {
// this.#value is not available here
}Expose protected behavior through public methods when subclasses genuinely need it.
Conclusion
Private fields and methods help classes maintain clear public APIs and hide implementation details. Use them for encapsulation, not as a replacement for authentication, encryption, or other security controls.