🟒 EasyObjectsπŸ“– Theory Question

What are getters and setters in JavaScript?

πŸ’‘

Hint

Accessor properties β€” run a function on read (get) or write (set)

Full Answer

Getters and setters are special methods that execute code when a property is read or written β€” they look like properties but behave like functions.

const user = {
  firstName: 'John',
  lastName: 'Doe',

  get fullName() {
    return `${this.firstName} ${this.lastName}`; // computed on read
  },

  set fullName(val) {
    [this.firstName, this.lastName] = val.split(' '); // validated on write
  }
};

console.log(user.fullName); // 'John Doe' β€” runs getter
user.fullName = 'Jane Smith'; // runs setter
console.log(user.firstName); // 'Jane'

// In a class
class Temperature {
  constructor(celsius) { this._c = celsius; }

  get fahrenheit() { return this._c * 9/5 + 32; }
  set fahrenheit(f) { this._c = (f - 32) * 5/9; }
}

const t = new Temperature(0);
console.log(t.fahrenheit); // 32
t.fahrenheit = 212;
console.log(t._c);         // 100
πŸ’‘ Use getters for derived/computed values. Use setters for validation. Avoid getter/setter pairs that call each other β€” infinite loops!

More Objects Questions

🟒 EasyHow does prototypal inheritance work in JavaScript?β†’πŸŸ’ EasyWhat is the difference between shallow copy and deep copy?β†’πŸŸ‘ MediumWhat are property descriptors and property flags (writable, enumerable, configurable)?β†’πŸŸ’ EasyWhat is the difference between Object.freeze() and Object.seal()?β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint