Object Getters & Setters in JavaScript
In JavaScript, getters and setters are special methods that allow you to control access to object properties. They make objects more dynamic and secure by letting you:
- Control how a property is read (getter)
- Control how a property is updated (setter)
Using getters and setters, you can add logic (like validation or computation) when accessing or modifying property values — instead of directly exposing them.
Getters
A getter allows you to define a method that’s called when a property is accessed.
Syntax:
const obj = {
firstName: "John",
lastName: "Doe",
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(obj.fullName); // "John Doe"
Setters
A setter defines a method that’s called when a property is assigned a value.
Syntax:
const obj = {
firstName: "John",
lastName: "Doe",
set fullName(name) {
const parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};
obj.fullName = "Jane Smith";
console.log(obj.firstName); // "Jane"
console.log(obj.lastName); // "Smith"
Getters & Setters Together
You can use both together to create controlled property access.
This approach makes fullName
behave like a normal property — but internally, it runs logic when read or written.
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(name) {
const [first, last] = name.split(" ");
this.firstName = first;
this.lastName = last;
}
};
person.fullName = "Alice Brown";
console.log(person.fullName); // "Alice Brown"
Using Object.defineProperty()
You can also define getters and setters using Object.defineProperty()
for more control (e.g., making them non-enumerable).
const user = { firstName: "John", lastName: "Doe" };
Object.defineProperty(user, "fullName", {
get() {
return `${this.firstName} ${this.lastName}`;
},
set(value) {
const [first, last] = value.split(" ");
this.firstName = first;
this.lastName = last;
}
});
console.log(user.fullName); // "John Doe"
user.fullName = "Mary Jane";
console.log(user.firstName); // "Mary"
Practical Use Cases
Use Case | Description |
---|---|
Data Validation | Check if the value being assigned is valid before updating. |
Computed Values | Combine or process multiple properties into one (e.g., fullName , totalPrice ). |
Encapsulation | Hide internal logic and expose a clean interface. |
Logging / Debugging | Track property changes for analytics or debugging. |
Example: Validation with Setter
_balance
is a private-like property (by convention, underscore _
), and the setter ensures that negative balances are not allowed.
const account = {
_balance: 0,
get balance() {
return this._balance;
},
set balance(amount) {
if (amount < 0) {
console.log("Invalid balance!");
} else {
this._balance = amount;
}
}
};
account.balance = 1000;
console.log(account.balance); // 1000
account.balance = -500; // "Invalid balance!"
Advantages
- Adds encapsulation (controls access to object properties).
- Enables data validation and transformation.
- Supports computed or derived values.
- Makes APIs cleaner by using property-like syntax.
Summary Table
Concept | Description | Example |
---|---|---|
Getter | Defines behavior when property is read | get fullName() { ... } |
Setter | Defines behavior when property is assigned | set fullName(name) { ... } |
Access | Use like a normal property | obj.fullName |
Define Property | Alternative definition method | Object.defineProperty() |