Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Private and static members

Not all of an object's data should be open to outside code. If anyone can write a negative number into an account balance, the object can hardly stay valid. Private fields hide data inside the class, and static members belong to the class itself rather than to its objects.

A private field

A field whose name starts with # is accessible only inside the class. From the outside it can be neither read nor changed:

class Account {
  #balance = 0;
 
  getBalance() {
    return this.#balance;
  }
}
 
const account = new Account();
 
console.log(account.getBalance()); // 0

Writing account.#balance outside the class is a syntax error: the program will not even start.

Encapsulation

Since a private field cannot be changed directly, it is changed through methods, and methods validate the data. Hiding data behind methods is called encapsulation:

class Account {
  #balance = 0;
 
  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  }
 
  getBalance() {
    return this.#balance;
  }
}
 
const account = new Account();
account.deposit(100);
account.deposit(-50);
 
console.log(account.getBalance()); // 100

The negative deposit was rejected: the object itself makes sure its data stays correct.

Private methods

The hash can also go before a method name. Such a method is an internal detail of the class and can only be called from its other methods:

class Order {
  constructor(price) {
    this.price = price;
  }
 
  #tax() {
    return this.price * 0.2;
  }
 
  total() {
    return this.price + this.#tax();
  }
}
 
console.log(new Order(100).total()); // 120

Static methods

A method marked static belongs to the class, not to its objects. It is called through the class name — helper functions and ways of creating objects are usually written like this:

class Temperature {
  static toFahrenheit(celsius) {
    return celsius * 1.8 + 32;
  }
}
 
console.log(Temperature.toFahrenheit(20)); // 68

You do not need to create an object to call a static method.

Static properties

A static property holds a value shared by the whole class. For example, a counter of created objects:

class User {
  static count = 0;
 
  constructor(name) {
    this.name = name;
    User.count++;
  }
}
 
new User('Anna');
new User('Oleg');
 
console.log(User.count); // 2

Common mistake

A static method cannot be called on an object — an instance simply does not have it:

class Temperature {
  static toFahrenheit(celsius) {
    return celsius * 1.8 + 32;
  }
}
 
const t = new Temperature();
 
console.log(typeof t.toFahrenheit);           // undefined
console.log(typeof Temperature.toFahrenheit); // function

If a method works with a particular object's data through this, it should not be static. If it does not need this, it can be static.

Thanks for reading!

Donate to the site — we work hard for you.