Getters & Setters in JavaScript

🎯 What are Getters & Setters?

Getters and setters are special methods in JavaScript that allow you to bind object properties to a function when that property is accessed or modified. They're typically used for encapsulation, validation, or computed values.

Note

💡 Getters use the get keyword, and setters use the set keyword. They let you control how properties are accessed or updated — behind the scenes!

📥 Defining a Getter

A getter is a method that gets the value of a property. It’s called like a property, not a function.

Getter Example

const user = {
  firstName: "John",
  lastName: "Doe",
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

console.log(user.fullName); // John Doe

📤 Defining a Setter

A setter is a method that sets the value of a property. Like getters, it's accessed like a property, but with assignment.

Setter Example

const user = {
  firstName: "John",
  lastName: "Doe",
  set fullName(name) {
    const parts = name.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
};

user.fullName = "Alice Smith";
console.log(user.firstName); // Alice
console.log(user.lastName);  // Smith

🏗️ Using Getters and Setters in Classes

Getters and setters are also very common in class definitions and can help encapsulate internal logic or validation.

Class-Based Getter/Setter

class Rectangle {
  constructor(width, height) {
    this._width = width;
    this._height = height;
  }

  get area() {
    return this._width * this._height;
  }

  set width(value) {
    if (value > 0) {
      this._width = value;
    }
  }
}

const r = new Rectangle(5, 10);
console.log(r.area); // 50
r.width = 7;
console.log(r.area); // 70

Note

⚠️ It’s a common convention to prefix internal properties with an underscore (e.g., _width) to differentiate them from their getter/setter counterparts.

🔍 When to Use

  • ✅ To compute a property dynamically.
  • ✅ To validate data before assignment.
  • ✅ To hide internal implementation details.
  • ✅ To mimic traditional OOP practices like encapsulation.

🧾 Summary

  • 🧠 Getters retrieve a computed or internal value.
  • 🛠️ Setters allow controlled updates with logic.
  • 🏛️ Useful in objects and classes for clean, readable access.

📚 Learn More

>>"Encapsulation is not hiding data — it's providing controlled access to it." 🔐