JavaScript Getters and Setters: Accessor Properties, Validation and Computed Values
Accessor properties in JavaScript: defining get and set in object literals, computed values that stay in sync, validating writes, read-only and write-only properties, inheritance, lazy getters, the infinite recursion trap, how copying and JSON treat accessors, and when not to use them.
kvi5hnuCode Sprout team member6 min readOn this page
Most properties are data properties: they hold a value. JavaScript also has accessor properties, which hold no value at all. Instead they have a getter function, called when the property is read, and/or a setter function, called when it's assigned. From outside, an accessor looks exactly like a normal property: rect.area, not rect.getArea().

Defining a getter
Prefix a method with get in an object literal (ES5):
const rect = {
width: 4,
height: 3,
get area() {
return this.width * this.height;
},
};
console.log(rect.area); // no parentheses: it's read like a property
rect.width = 10;
console.log(rect.area); // recomputed on every read
12
30
This is the main reason getters exist: a derived value that can never be out of date. If area were a data property set once, it would go stale the moment width changed.
Adding a setter
Prefix a method taking one parameter with set. Assigning to the property calls it with the assigned value:
const thermostat = {
celsius: 20,
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
},
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
},
};
thermostat.fahrenheit = 212;
console.log(thermostat.celsius, thermostat.fahrenheit);
100 212
There's one stored value, celsius, and two views of it. Whichever one you write, both stay consistent.
Syntax rules: a getter takes no parameters and a setter takes exactly one, otherwise it's a SyntaxError. The getter and setter share a name, and the names can be computed: get [key]() {}. The setter's return value is ignored; an assignment expression always evaluates to the right-hand side.
Read-only and write-only
- Getter only: the property is read-only. Assigning to it fails: silently in sloppy mode, with a
TypeErrorin strict mode (article 47). - Setter only: the property is write-only, and reading it gives
undefined. That's rarely useful.
(function () {
"use strict";
const circle = { radius: 2, get diameter() { return this.radius * 2; } };
try {
circle.diameter = 10;
} catch (err) {
console.log(err.name);
}
console.log(circle.diameter);
})();
TypeError
4
Validating writes
A setter can check values before storing them, and keep an object's data consistent no matter who assigns to it:
const account = {
_age: 0,
get age() {
return this._age;
},
set age(value) {
if (!Number.isInteger(value) || value < 0) {
throw new RangeError(`invalid age: ${value}`);
}
this._age = value;
},
};
account.age = 30;
try {
account.age = -1;
} catch (err) {
console.log(err.name, err.message);
}
console.log(account.age);
RangeError invalid age: -1
30
The value lives in a backing property, here _age. The underscore is only a naming convention meaning "internal, please don't touch"; anyone can still write account._age = -5 and bypass the check. Real privacy needs class private fields (#age, part 9) or a closure (part 8).
The infinite recursion trap
A getter that reads its own name calls itself forever, and a setter that assigns to its own name does the same:
const broken = {
get total() {
return this.total; // reads total, which calls the getter, which reads total...
},
};
try {
broken.total;
} catch (err) {
console.log(err.name); // "Maximum call stack size exceeded"
}
RangeError
Always store the data under a different name than the accessor (_total, #total in a class) or compute it from other properties.
Getters with side effects
A getter runs code on every read, so it can return a different value each time:
const ticketMachine = {
_next: 100,
get next() {
return this._next++;
},
};
console.log(ticketMachine.next, ticketMachine.next, ticketMachine.next);
100 101 102
It works, but it surprises readers: x.next === x.next is false, and merely inspecting the object in a debugger can change it. Make it a method (takeTicket()) when reading has side effects. Getters should be cheap and feel like reading data.
Lazy getters: compute once, on first use
For an expensive value that might never be needed, a getter can compute it on first access and then replace itself with a plain data property holding the result:
const report = {
get stats() {
console.log("computing...");
const value = [3, 1, 2].sort((a, b) => a - b);
Object.defineProperty(this, "stats", { value, writable: false });
return value;
},
};
console.log(report.stats);
console.log(report.stats); // no "computing..." the second time
computing...
[ 1, 2, 3 ]
[ 1, 2, 3 ]
Browsers and Node.js use this pattern internally for some built-in properties.
Accessors are inherited
Getters and setters are properties like any other, so objects inherit them through the prototype chain, and inside them, this is the object you accessed the property on:
const personProto = {
get fullName() {
return `${this.first} ${this.last}`;
},
set fullName(text) {
[this.first, this.last] = text.split(" ");
},
};
const ada = Object.create(personProto);
ada.fullName = "Ada Lovelace"; // inherited setter; data lands on ada
console.log(ada.first, Object.keys(ada), ada.fullName);
Ada [ 'first', 'last' ] Ada Lovelace
This is how class getters and setters work (part 9): defined once on the prototype, used by every instance. Many built-ins are accessors too: map.size, array.buffer on typed arrays, element.innerHTML in the DOM.
How accessors behave when copied or serialized
Spread, Object.assign and JSON.stringify all read properties, so they call getters and store the current value as plain data:
const box = { side: 2, get area() { return this.side ** 2; } };
const copy = { ...box };
copy.side = 10;
console.log(copy.area, typeof Object.getOwnPropertyDescriptor(copy, "area").get);
console.log(JSON.stringify(box));
const real = Object.defineProperties({}, Object.getOwnPropertyDescriptors(box));
real.side = 10;
console.log(real.area);
4 undefined
{"side":2,"area":4}
100
The spread copy froze area at 4. To copy accessors as accessors, copy the property descriptors with Object.getOwnPropertyDescriptors and Object.defineProperties. Part 14 covers descriptors and Object.defineProperty, which can also add getters and setters to existing objects.
When to use accessors
Good uses:
- Derived values that must stay in sync with other data (
area,fullName,isEmpty,total). - Validation or normalization on assignment (
emaillowercased and checked). - Backward compatibility: turning an existing data property into computed logic without changing any code that uses it.
- Read-only views of internal state.
Avoid them for expensive work (readers expect property access to be fast), for anything with side effects, and for operations that can fail for reasons other than bad input, such as network calls. Those should be methods, so that the call is visible at the call site.
Common questions
Getter or method: user.fullName or user.getFullName()?
Both are fine. Use a getter when the value feels like an attribute of the object, is cheap and has no side effects; use a method when it takes arguments, does real work, or might fail.
Why does console.log(obj) show [Getter] or [Getter/Setter]?
Node.js's inspector doesn't call getters by default, because calling them could have side effects. Browser consoles show (...) and call the getter when you click it.
Are accessor properties enumerable?
Ones defined in object literals are, so they appear in Object.keys and JSON.stringify output. Getters defined in classes live on the prototype and are non-enumerable, so they don't.
Can I add a getter to an existing object?
Yes: the code below. Part 14 covers the details.
Object.defineProperty(obj, "name", { get() { ... }, enumerable: true, configurable: true })
Summary
- Accessor properties have a getter and/or setter instead of a value; they're read and assigned like normal properties.
get name() {}computes a value on every read;set name(v) {}receives assigned values; a getter alone makes the property read-only.- Setters are the place to validate and normalize; store the data in a separately named backing property.
- Reading or assigning the accessor's own name inside it causes infinite recursion.
- Lazy getters compute once and replace themselves with a data property.
- Accessors are inherited and run with
thisset to the accessed object. - Spread,
Object.assignand JSON copy the getter's current value; copy property descriptors to keep accessors.
Practice Questions
What does this print?
const o = { n: 2, get sq() { return this.n * this.n; } };
o.n = 5;
console.log(o.sq, Object.keys(o));
Answer
25 [ 'n', 'sq' ]. The getter runs on each read, using the current n, and literal accessors are enumerable.
Write an object with a celsius data property and a read-only kelvin getter.
Answer
const t = { celsius: 25, get kelvin() { return this.celsius + 273.15; } };
Assigning t.kelvin = 0 fails: silently in sloppy mode, with a TypeError in strict mode.
What's wrong with this code?
const u = { set name(v) { this.name = v.trim(); } };
Answer
The setter assigns to this.name, which calls the setter again, recursing until a RangeError. Store the value under another key: this._name = v.trim();, and add a matching getter.
After this code, copy.total no longer updates when items change. Why?
const copy = { ...original }
Answer
Spread read original.total once, calling the getter, and stored the result as a plain data property. Copy descriptors with the code below to keep the getter.
Object.defineProperties({}, Object.getOwnPropertyDescriptors(original))
Review quiz
You've finished Part 6. Check your understanding with the Objects review quiz: 25 questions on creating objects and prototypes, reading and writing inherited properties, testing and listing keys, Object.assign and spread, JSON, toString and valueOf, modern literal syntax, and getters and setters.
Previous: JavaScript Object Literal Syntax: Shorthand Properties, Computed Keys, Methods and Spread
Next: JavaScript Arrays: Creating Arrays with Literals, Spread, Array.of and Array.from

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.