Getters & Setters

Getters and setters are special methods in JavaScript objects that allow controlled access to object properties.

Illustration of getters_setters
Illustration of getters_setters

💡 What are Getters & Setters?

Getters allow you to define a method that runs when a property is accessed. Setters run when a property is assigned a value. This lets you add logic during property access or update.

They help keep properties private or computed, provide validation, or trigger side effects.

Basic Syntax
GetterSetter
get propName() { ... } set propName(value) { ... }

📌 Deep Dive: Using Getters & Setters

JAVASCRIPT
const person = {
  firstName: 'John',
  lastName: 'Doe',

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },

  set fullName(name) {
    const parts = name.split(' ');
    this.firstName = parts[0];
    this.lastName = parts[1] || '';
  }
};

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

person.fullName = 'Jane Smith';
console.log(person.firstName);   // Jane
console.log(person.lastName);    // Smith
Output
John Doe
Jane
Smith

💡 Why use Getters & Setters?

  • Encapsulation: Hide internal representation of data.
  • Validation: Validate or modify data before setting.
  • Computed properties: Calculate values on the fly.
  • Debugging: Easily log or watch property access.

⚠️ Important

Getters should not have side effects and should return a value quickly. Setters must accept exactly one argument.

Getters & Setters vs Regular Properties
FeatureRegular PropertyGetter/Setter
AccessDirect valueRuns code
ModificationDirect assignmentRuns code with validation
ComputedNoYes
Side EffectsPossibleNot recommended for getters

💡 Quick Tip

You can define getters/setters in object literals, classes, or via Object.defineProperty().

📌 Deep Dive: Getters & Setters in Classes

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

  get area() {
    return this.width * this.height;
  }

  set area(value) {
    throw new Error('Area is read-only!');
  }
}

const rect = new Rectangle(4, 5);
console.log(rect.area);  // 20
// rect.area = 30;       // Error: Area is read-only!
Output
20

⚠️ Avoid Infinite Loops

Inside setters or getters, be careful not to assign or access the same property directly; use a different property name to avoid recursion.