If JavaScript objects were people, properties would be their “things”—
like name, age, or the number of pani-puris they can eat 🍽️
But sometimes, you want a little control when someone tries to read or change these properties.
That’s where Getters and Setters come in…
Think of them as friendly bodyguards standing at the door of your object.
They make sure only valid, clean, and expected values enter… and leave!
Let’s break this down in the easiest way possible 💡
🧠 What Are Getters and Setters?
Getter → when you get a value
It lets you read a property in a controlled way.
Setter → when you set a value
It lets you update a property safely (and reject bad inputs).
🎯 Why Do We Even Need Them?
Because they give you:
✔ Control over how values are read
✔ Validation before updating values
✔ Cleaner syntax
✔ Ability to compute or transform values on the fly
📦 Simple Example: A User Profile
class User {
constructor(name) {
this._name = name; // internal property
}
get name() {
return this._name.toUpperCase(); // transform before returning
}
set name(value) {
if (!value.trim()) {
console.log("Name cannot be empty!");
return;
}
this._name = value;
}
}
const u = new User("Amit");
console.log(u.name); // AMIT
u.name = ""; // Name cannot be empty!
u.name = "Sharma";
console.log(u.name); // SHARMA
✔ Getter transforms output
✔ Setter validates input
🚗 Real-Life Example: Car Speed Control
class Car {
constructor() {
this._speed = 0;
}
get speed() {
return `${this._speed} km/h`;
}
set speed(value) {
if (value < 0) {
console.log("Speed cannot be negative!");
return;
}
this._speed = value;
}
}
const c = new Car();
c.speed = 40;
console.log(c.speed); // 40 km/h
c.speed = -10; // Speed cannot be negative!
This is how real apps ensure safe input — like preventing a website from having a negative price 😅
🔒 Getters & Setters + Private Fields = Clean Code
Combine them with modern # private fields for maximum power:
class BankAccount {
#balance = 0;
get balance() {
return this.#balance;
}
set balance(amount) {
if (amount < 0) {
console.log("Invalid amount!");
return;
}
this.#balance = amount;
}
}
const acc = new BankAccount();
acc.balance = 500;
console.log(acc.balance); // 500
This is ideal for sensitive logic—like money, passwords, points, etc.
🔧 When Should You Use Getters & Setters?
Use them when you want to:
✔ Validate input
✔ Hide implementation details
✔ Format values before showing
✔ Automatically calculate values
✔ Keep your code future-proof
🏁 Final Thoughts
Getters and setters might look fancy, but they’re simply smart doors to your object properties.
They give you:
✨ Cleaner code
✨ Better control
✨ Easier maintenance
✨ Safer data handling
If you love writing neat, professional JavaScript…
you’ll love getters and setters ❤️

Leave a Reply