Intermediate LevelJavaScript & TypeScript
What are JavaScript getters and setters in objects and classes?
❓ Interview Prompt: Explain get and set accessor keywords, computed properties, and Object.defineProperty property descriptors.
Getters (`get`) and Setters (`set`) bind an object property to a function that executes when the property is read or written.
Benefits:
1
Encapsulation: Perform data validation or transformations on property updates without changing external caller syntax.
2
Computed Properties: Expose dynamic computed values as standard object properties.
3
Property Descriptors: Configurable via
Object.defineProperty(obj, prop, descriptor) to set enumerable, configurable, writable.Code Implementation Example
javascript
class UserAccount {
#balance = 0; // Private class field
constructor(initialBalance) {
this.#balance = initialBalance;
}
// Getter: read balance as formatted currency
get formattedBalance() {
return `$${this.#balance.toFixed(2)}`;
}
// Setter: validate before writing
set balance(amount) {
if (amount < 0) throw new RangeError('Balance cannot be negative');
this.#balance = amount;
}
}
const account = new UserAccount(100);
console.log(account.formattedBalance); // "$100.00"
account.balance = 250; // Triggers setter validation!💡Getter for formatted string output and setter for validation on private class state.
🎯 Interview Key Takeaway
Getters and setters wrap property access with custom logic, allowing validation and computed values without modifying call syntax.
#Getters Setters#Encapsulation#Classes#Intermediate
Back to all JavaScript & TypeScript Questions→