Why use getters and setters in JavaScript?

A difference between using a getter or setter and using a standard function is that getters/setters are automatically invoked on assignment. So it looks just like a normal property but behind the scenes you can have extra logic (or checks) to be run just before or after the assignment.

So if you decide to add this kind of extra logic to one of the existing object properties that is already being referenced, you can convert it to getter/setter style without altering the rest of the code that has access to that property.

Edit: Here is an example for an extra logic, this class counts how many times its name is read:

class MyClass {
  constructor() {
    this.refCount = 0;
    this._name="the class";
  }

  get name() {
    this.refCount++;
    console.log(`name is read ${this.refCount} times.`);
    return this._name;
  }
}

const myClass = new MyClass();

let maxMessages = 5;
const t = setInterval(() => {
  console.log(`name: ${myClass.name}`);
  
  if (--maxMessages < 1) {
    console.log('done');
    clearInterval(t);
  }
}, 1000);

Leave a Comment

tech