What will be displayed when a setter validation fails?
const user = {
get name() {
return this._name;
},
set name(value) {
if (value.length < 3) {
throw new Error('Name too short');
}
this._name = value;
}
};
user.name = 'John';
console.log(user.name);
try {
user.name = 'Jo';
} catch (e) {
console.log(e.message);
}
The code will log 'John' and 'Name too short' because: 1) The first assignment user.name = 'John' passes validation and is stored, 2) The getter returns the stored value when console.log(user.name) is called, 3) The second assignment user.name = 'Jo' triggers validation in the setter, 4) Since 'Jo' is less than 3 characters, the setter throws an error, 5) The catch block catches this error and logs its message, 6) This demonstrates how accessor properties can perform validation to enforce business rules, 7) The internal _name property stores the actual data while the accessors provide a controlled interface.