A setter is a method that sets the value of a specific property. It allows you to assign a value to a property using a function, enabling data validation, transformation, or other logic when the property is set.
let obj = {
set propertyName(value) {
// code to set the property value
}
};
let person = {
firstName: 'John',
lastName: 'Doe',
set fullName(name) {
let parts = name.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
};
person.fullName = 'Jane Smith';
console.log(person.firstName); // Output: Jane
console.log(person.lastName); // Output: Smith