We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Private Properties

By default, all properties of a class are public, meaning they can be accessed and modified from outside the class. Here's an example:

class Movie {
  constructor(title, rating) {
    this.title = title;
    this.rating = rating;
  }
}

const matrixMovie = new Movie("The Matrix", 9.5);
console.log(matrixMovie.title);
// The Matrix
matrixMovie.title = "The Matrix Reloaded";
console.log(matrixMovie.title);
// The Matrix Reloaded

Maybe we don't want our title to be able to be changed anywhere in our code. We can make it private by prefixing it with a hash # and declaring it at the top of the class:

class Movie {
  #title;
  constructor(title, rating) {
    this.#title = title;
    this.rating = rating;
  }
}

const matrixMovie = new Movie("The Matrix", 9.5);
console.log(matrixMovie.#title);
// Uncaught SyntaxError: Private field '#title' must be declared in an enclosing class

Private properties can still be used from within the class:

class Movie {
  #title;
  constructor(title, rating) {
    this.#title = title;
    this.rating = rating;
  }

  getTitleAllCaps() {
    const allCaps = this.#title.toUpperCase();
    return allCaps;
  }
}

const matrixMovie = new Movie("The Matrix", 9.5);
console.log(matrixMovie.getTitleAllCaps());
// THE MATRIX

Encapsulation in JavaScript is typically enforced at two levels:

  • The class level: Public/private methods using # for private fields
  • The module level: Exporting only what you want to be public (we'll talk about modules later)

Assignment

Textio messages have a createdAt field that stores the date the message was created. In order to avoid accidentally altering the creation date, change the createdAt field from a public field to a private field.