โ 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
fullName
like 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
โ ๏ธ
set
must 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:
width
andheight
properties- A getter
area
that returnswidth * height
- A setter
dimensions
that 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!