Skip to content

OutputNot attempted

Getters and setters

const user = {
first: 'John',
last: 'Doe',
get full() {
return this.first + ' ' + this.last;
},
set full(v) {
[this.first, this.last] = v.split(' ');
},
};
console.log(user.full);
user.full = 'Alice Wonderland';
console.log(user.first, user.full);
const circle = { r: 1, get area() { return 3 * this.r ** 2; } };
try {
circle.area = 100;
} catch (e) {
console.log(e.name);
}
console.log(circle.area, Object.keys(user));

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

Accessors run code on read/write. A getter WITHOUT a setter is read-only: assigning to it throws TypeError in strict mode (silently ignored in sloppy). Accessor properties are enumerable by default when defined in a literal, so full shows up in keys.