Getters and setters in JavaScript provide controlled access to an object’s properties. Instead of reading or modifying data directly, they allow developers to run custom logic whenever a property is accessed or changed. This helps with validation, formatting, calculations, and maintaining clean, maintainable code.
For simple objects, direct property access is often sufficient. However, getters and setters become valuable when a property requires additional processing or protection.
What Are Getters And Setters?
A getter is a method that runs when a property is read, while a setter runs when a property is assigned a value.
Example:
const user = {
firstName: "John",
lastName: "Doe",
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); // John Doe
user.fullName = "Jane Smith";
console.log(user.firstName); // Jane
To the outside world, fullName behaves like a normal property, even though methods are running behind the scenes.
Encapsulate Internal Logic
One of the biggest benefits of getters and setters is encapsulation. They hide implementation details while providing a simple interface.
Instead of exposing how data is stored internally, you expose how it should be used.
For example:
class Product {
constructor(price) {
this._price = price;
}
get price() {
return this._price;
}
set price(value) {
if (value < 0) {
throw new Error("Price cannot be negative");
}
this._price = value;
}
}
The validation happens automatically whenever someone tries to update the price.
Validate Data Automatically
Setters are commonly used to validate incoming values before storing them.
This can help prevent:
- Invalid input
- Negative values where they are not allowed
- Incorrect data types
- Empty required fields
Rather than checking data throughout an application, validation can be centralized in the setter.
Create Computed Properties
Getters are useful when a property’s value depends on other properties.
For example:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
const rect = new Rectangle(10, 5);
console.log(rect.area); // 50
The area is calculated only when needed and does not have to be stored separately.
Improve Code Readability
Without getters, developers often create methods such as:
user.getFullName();
With a getter:
user.fullName;
Many developers find property-style access easier to read because it feels more natural and concise.
Maintain Backward Compatibility
Getters and setters can help when updating an application’s internal structure.
Suppose a property was originally stored directly:
user.name
Later, additional processing becomes necessary. A getter or setter can be added without changing code that already uses the property.
This allows the internal implementation to evolve while preserving the public API.
When Not To Use Getters And Setters
While useful, they should not be added everywhere.
Direct properties are often better when:
- No validation is needed
- No calculations are performed
- No special processing is required
- Simplicity is more important
Overusing getters and setters can make code harder to understand and debug.
Important Considerations
Before implementing getters and setters, think about whether additional logic is truly needed.
They work best when:
- Data requires validation
- Values are computed dynamically
- Internal implementation should remain hidden
- Future flexibility is important
For simple data containers, direct property access is often the cleaner choice.
Join The Discussion
How do you use getters and setters in your JavaScript projects? Do you primarily use them for validation, computed properties, encapsulation, or API design? Share your coding practices, examples, and experiences to help other developers understand when getters and setters are worth using.