JavaScript Getters and Setters: Accessor Properties
Quick answer
An accessor property runs a getter on read or a setter on assignment instead of storing a data value in that property.
How it works
Object literal accessors use get name() { ... } and set name(v) { ... }. A getter has no parameters; a setter has exactly one formal parameter. They receive the ordinary property receiver as this, including inherited accessors. A setter’s return value does not become the result of an assignment expression. A getter-only property rejects assignment in strict code.
const box = {width: 3, height: 4, get area() { return this.width * this.height; }};console.log(box.area);Expected output in Node.js:
12Property access invokes the getter without explicit parentheses.
const box = {_n: 0, set count(v) { this._n = Math.max(0,v); }, get count() { return this._n; }};box.count = -4; console.log(box.count);Expected output in Node.js:
0The setter clamps the stored backing value.
Common mistakes
A setter that assigns its own accessor name recursively invokes itself. Store data in a different field.
Practice
Add a setter that stores a normalized nonnegative count in a separate property.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Getters and Setters: Accessor Properties — Knowledge Check
Apply the taught concept and predict the output.
How many formal parameters does getter syntax allow?
Which receiver is used by an inherited ordinary getter?
What happens when a setter assigns its own accessor name without a guard?
What is the exact console output in JavaScript Getters and Setters: Accessor Properties example 1?
const box = {width: 3, height: 4, get area() { return this.width * this.height; }};console.log(box.area);What is the exact console output in JavaScript Getters and Setters: Accessor Properties example 2?
const box = {_n: 0, set count(v) { this._n = Math.max(0,v); }, get count() { return this._n; }};box.count = -4; console.log(box.count);