Private Properties
By default, all properties of a JavaScript class are public. This means they can be accessed and modified from anywhere outside the class.
class Movie {
constructor(title, rating) {
this.title = title;
this.rating = rating;
}
}
const matrixMovie = new Movie("The Matrix", 9.5);
// Anyone can change this property!
matrixMovie.title = "The Matrix Reloaded";
Creating Private Properties
Sometimes, you need to protect internal state so it cannot be accidentally altered by other parts of the application. This is a core concept of Object-Oriented Programming called Encapsulation.
In modern JavaScript, you make a property private by prefixing it with a hash (#). You must declare these private fields at the top of the class body before using them in the constructor.
class Movie {
// Declare the private field
#title;
constructor(title, rating) {
this.#title = title;
this.rating = rating;
}
// Private fields can be used freely INSIDE the class
getTitleAllCaps() {
return this.#title.toUpperCase();
}
}
const matrixMovie = new Movie("The Matrix", 9.5);
// Allowed: Accessing via a public method
console.log(matrixMovie.getTitleAllCaps()); // Output: "THE MATRIX"
// Blocked: Attempting to access the private field directly
console.log(matrixMovie.#title);
// Uncaught SyntaxError: Private field '#title' must be declared in an enclosing class
By making the field private, you guarantee that the underlying data cannot be tampered with directly.