Smart Properties
In JS, there are two types of properties: data properties (regular ones) and accessor properties. Accessors are functions that trigger when a value is read or written.
let user = {
name: "John",
surname: "Smith",
get fullName() {
return `${this.name} ${this.surname}`;
},
set fullName(value) {
[this.name, this.surname] = value.split(" ");
}
};
Why is this needed?
- Validation: You can prevent setting a name that is too short in the
setmethod. - Compatibility: You can replace a normal property with a getter so old code still works, but the internal logic has changed.
Tip
Getters and setters look like regular properties from the outside (user.fullName), but they give you full control over what happens under the hood.