Getters, Setters & Static

get and set

Example

Getters and setters look like properties but run code, for computed values and validation:

class Temperature {
  constructor(celsius) { this.celsius = celsius; }
  get fahrenheit() { return this.celsius * 9 / 5 + 32; }
  set fahrenheit(f) { this.celsius = (f - 32) * 5 / 9; }
}
const t = new Temperature(25);
console.log(t.fahrenheit);
t.fahrenheit = 212;
console.log(t.celsius);

Output

77
100

static Members

Example

Static methods and properties belong to the class itself, not to instances, e.g. factory functions and helpers:

class User {
  static count = 0;
  constructor(name) { this.name = name; User.count++; }
  static fromEmail(email) { return new User(email.split("@")[0]); }
}
const u = User.fromEmail("[email protected]");
new User("Vikram");
console.log(u.name, User.count);

Output

asha 2