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,
- They provide simpler syntax
- They are used for defining computed properties, or accessors in JS.
- Useful to provide equivalence relation between properties and methods
- They can provide better data quality
- 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