Hiprup

What are getter and setter properties?

Getters and setters let you define methods that are accessed like properties, adding logic behind reading or writing a value.

  • get — runs when the property is read; often returns a computed value.

  • set — runs when the property is assigned; good for validation or side effects.

Benefit: a clean property-like API with hidden logic — no method-call parentheses needed.

class Circle {
  constructor(radius) {
    this._radius = radius; // Convention: _ for backing field
  }

  get radius() { return this._radius; }

  set radius(value) {
    if (value < 0) throw new Error('Radius must be positive');
    this._radius = value;
  }

  get area() { // Computed property (read-only)
    return Math.PI * this._radius ** 2;
  }

  get diameter() { return this._radius * 2; }
  set diameter(d) { this._radius = d / 2; }
}

const c = new Circle(5);
console.log(c.radius);   // 5 (getter)
console.log(c.area);     // 78.54 (computed)
c.diameter = 20;          // setter: radius becomes 10
console.log(c.radius);   // 10
// c.radius = -1;         // Error: Radius must be positive

get radius returns _radius. set radius validates before assigning. get area computes from radius (read-only — no setter). diameter has both get and set — setting diameter adjusts radius. Properties are accessed like normal attributes (c.area, not c.area()).

Show validation in setter (the most practical use), computed properties (area from radius), and read-only (getter without setter). Accessed like properties (c.area not c.area()).

In classes and object literals.

What are getter and setter properties? | Hiprup