InterviewHubPRO
Section Overview
Q224

Question 224 of 521

Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

43%
JavaScript Internals (521 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

What are the advantages of Getters and Setters

Below are the list of benefits of Getters and Setters,

  1. They provide simpler syntax
  2. They are used for defining computed properties, or accessors in JS.
  3. Useful to provide equivalence relation between properties and methods
  4. They can provide better data quality
  5. Useful for doing things behind the scenes with the encapsulated logic.

Practical Code Example

javascript
// Advantages of Getters & Setters:
// 1. Data Validation: Validate inputs before saving
// 2. Encapsulation: Compute virtual properties on the fly without breaking external API
class BankAccount {
  #balance = 0;

  get balance() { return this.#balance; }
  set balance(amount) {
    if (amount < 0) throw new Error('Balance cannot be negative');
    this.#balance = amount;
  }
}
const acc = new BankAccount();
acc.balance = 100;
console.log(acc.balance); // 100