Defining Setters with the 'set' Keyword
You'll learn how to use the set keyword to run custom logic whenever someone tries to assign a value to an object property.
What Is a Setter?
A setter is a special method that intercepts property assignments. When you use the set keyword before a method name, that method runs automatically whenever someone tries to assign a value to that property. It's like having a gatekeeper who checks or transforms incoming data before storing it.
Think of it like a mailbox with a built-in filter: instead of mail going directly into the box, it passes through a slot where it can be inspected, rejected, or modified first.
Basic Syntax
const person = {
firstName: 'Jane',
lastName: 'Doe',
set fullName(value) {
const parts = value.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
};
person.fullName = 'John Smith'; // Setter runs automatically
console.log(person.firstName); // "John"
console.log(person.lastName); // "Smith"
When you assign person.fullName = 'John Smith', it looks like a simple property assignment, but the set fullName() method intercepts it, splits the string, and updates firstName and lastName separately.
Common Use Cases
Setters are perfect for:
- Validation: Check if incoming values are valid before storing them
- Transformation: Convert or format data before assignment
- Side effects: Update related properties or trigger other actions
- Controlled access: Prevent direct modification of internal properties
Key Takeaway: The set keyword creates setter methods that intercept property assignments, letting you validate, transform, or react to incoming values before they're stored—making property assignment look simple while adding powerful logic behind the scenes.