When to Use Getters/Setters vs Plain Properties
You'll learn: When to choose accessors (getters/setters) over plain properties and understand the trade-offs.
The Core Decision
Not every property needs getters and setters. Plain properties are perfect for simple data storage—when you just need to hold a value without any special behavior. Getters and setters shine when you need validation, computation, or side effects.
Think of plain properties like a basic storage box: you put something in, you take it out. Getters and setters are like a smart container with built-in rules—they can check what goes in, transform what comes out, or trigger actions when accessed.
When to Use Plain Properties
Use plain properties when:
- You're storing simple data with no special requirements
- Performance matters (direct access is faster)
- The value doesn't need validation or transformation
- You want straightforward, readable code
const user = {
name: 'Alice',
age: 30,
email: 'alice@example.com'
};
When to Use Getters/Setters
Use accessors when you need to:
- Validate data before storing (age must be positive)
- Compute values on-the-fly (fullName from firstName + lastName)
- Control access (read-only properties via getter without setter)
- Trigger side effects (logging, updating UI when values change)
const person = {
_age: 30,
get age() {
return this._age;
},
set age(value) {
if (value < 0) throw new Error('Age cannot be negative');
this._age = value;
}
};
Key Takeaway: Use plain properties for straightforward data storage. Use getters/setters when you need validation, computation, or special behavior—but don't over-engineer simple cases.