JS Built-ins
Prototypesintermediate

Prototypes β€” Getters and setters

πŸ“– Usage Example
class Circle {
  #r;
  constructor(r) { this.#r = r; }
  get radius() { return this.#r; }
  set radius(v) { if (v > 0) this.#r = v; }
}
const c = new Circle(5);
c.radius; // 5

Getters and setters let you control how properties are read and written.

Using get and set Keywords

Classes support getter and setter syntax using the get and set keywords. Getters allow you to compute values, and setters allow you to validate or transform data when properties are assigned.

Challenge: Create a class with getter and setter to manage a computed property with validation.

πŸ’‘ Hints (3)
  • β€’ get keyword defines a property getter
  • β€’ set keyword defines a property setter
  • β€’ Use _ prefix convention for internal properties