β What are Getters and Setters?
- Getter (
get): Returns the value of a property. - Setter (
set): Sets or updates the value of a property.
They are defined inside objects and are used like regular properties, but work like functions behind the scenes.
π 1. Basic get Example
jsCopyEditconst person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.fullName); // John Doe
π You access
fullNamelike a property, but it’s actually a method usingget.
π 2. Basic set Example
jsCopyEditconst person = {
firstName: "John",
lastName: "Doe",
set fullName(name) {
const [first, last] = name.split(" ");
this.firstName = first;
this.lastName = last;
}
};
person.fullName = "Jane Smith";
console.log(person.firstName); // Jane
console.log(person.lastName); // Smith
β οΈ
setmust accept exactly one parameter.
π 3. Combining get and set
jsCopyEditconst user = {
firstName: "Alice",
lastName: "Brown",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(value) {
const parts = value.split(" ");
this.firstName = parts[0];
this.lastName = parts[1] || "";
}
};
console.log(user.fullName); // Alice Brown
user.fullName = "Emily Davis";
console.log(user.fullName); // Emily Davis
π 4. Why Use Getters and Setters?
| Use Case | Benefit |
|---|---|
| Encapsulation | Hide internal structure |
| Input validation | Check/set only valid values |
| Computed properties | Return derived values dynamically |
| Logging/debugging | Add logs every time a property is accessed or set |
π 5. Example: With Validation
jsCopyEditconst account = {
_balance: 1000,
get balance() {
return this._balance;
},
set balance(amount) {
if (amount < 0) {
console.log("Invalid amount");
return;
}
this._balance = amount;
}
};
console.log(account.balance); // 1000
account.balance = -500; // Invalid amount
console.log(account.balance); // 1000
account.balance = 2000;
console.log(account.balance); // 2000
π Convention: use
_prefix (like_balance) for internal/private properties.
π§ͺ Practice Challenge
Create a rectangle object with:
widthandheightproperties- A getter
areathat returnswidth * height - A setter
dimensionsthat sets both width and height via a string like"10x5"
Would you like this as:
- π» Interactive JS Fiddle/CodePen link?
- π Downloadable PDF or notes?
- π Flashcards for revision?
Let me know and I can generate it for you!