SyntaxStudy
Sign Up
JavaScript Intermediate 8 min read

Getters and Setters

Getters and Setters

Getters and setters let you define properties that execute code when they are read or written, while presenting a clean property access syntax to callers. They are defined with the get and set keywords in a class body or object literal.

Getters

A getter is a method that is called when its property is accessed. Define it with get propertyName() { }. It must not take any parameters and should return a value. Use getters for computed or derived properties — values that depend on other state.

Setters

A setter is called when its property is assigned. Define it with set propertyName(value) { }. It takes exactly one parameter. Use setters to validate or transform values before storing them.

Backing Store Pattern

Getters and setters typically store the actual value in a private backing field (using a private field #field or a naming convention like _field) to avoid infinite recursion when the getter/setter accesses the same property name.

Example
class Temperature {
  #celsius;
  constructor(celsius) {
    this.#celsius = celsius;
  }
  get celsius() { return this.#celsius; }
  set celsius(value) {
    if (value < -273.15) throw new RangeError('Below absolute zero');
    this.#celsius = value;
  }
  get fahrenheit() { return this.#celsius * 9 / 5 + 32; }
  set fahrenheit(value) { this.celsius = (value - 32) * 5 / 9; }
  get kelvin() { return this.#celsius + 273.15; }
}
const t = new Temperature(100);
console.log(t.celsius);     // 100
console.log(t.fahrenheit);  // 212
console.log(t.kelvin);      // 373.15
t.fahrenheit = 32;
console.log(t.celsius);     // 0
Pro Tip

Getters are perfect for computed properties that should look like simple data to the outside world — the caller does not need to know or care whether a property is stored directly or calculated on demand.