Course contentsShow
← JavaScript
Lesson 1834 of 2,72338. Object-Oriented PatternsFree lesson

Getters and Setters for Controlled Access

Wrapping private state with get/set accessors to validate and transform data on read or write.

Getters and Setters for Controlled Access

You'll learn how to use get and set accessors to control how data is read from and written to objects, enabling validation and transformation.

What Are Getters and Setters?

Getters and setters are special methods that intercept property access. Instead of directly reading or writing a value, you can run code that validates, transforms, or logs the operation. Think of them as gatekeepers: they stand between the outside world and your internal data, ensuring everything follows the rules.

Why Use Them?

When combined with private fields or closures, getters and setters let you:

  • Validate data before storing it (e.g., reject negative ages)
  • Transform data on read or write (e.g., always return uppercase)
  • Compute values on-the-fly instead of storing them
  • Protect internal state from invalid changes

Syntax with Classes

class User {
  #age; // private field

  get age() {
    return this.#age;
  }

  set age(value) {
    if (value < 0) {
      throw new Error('Age cannot be negative');
    }
    this.#age = value;
  }
}

const user = new User();
user.age = 25;      // Calls the setter, validates
console.log(user.age); // Calls the getter, returns 25
// user.age = -5;   // Would throw error

With Object Literals

const circle = {
  _radius: 0,
  get radius() {
    return this._radius;
  },
  set radius(value) {
    if (value < 0) throw new Error('Radius must be positive');
    this._radius = value;
  },
  get area() {
    return Math.PI * this._radius ** 2; // Computed on access
  }
};

Key Takeaway: Getters and setters wrap private or sensitive data with validation and transformation logic, giving you full control over how properties are accessed and modified while maintaining a clean, property-like interface.