Getters, Setters and Class Patterns
Accessors let a method be read like a property, and combined with private fields they give you controlled, validated state.
A getter runs on read and a setter runs on write, while looking exactly like a plain property at the call site. Together with # fields they let a class validate every change, expose computed values, and keep its internals free to change.
EXERCISE
1A Method That Looks Like a Property
Accessors let you change how a value is produced without changing any of the code that reads it.
The syntax, and what it buys you:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
const r = new Rectangle(3, 4);
console.log(r.area); // 12 no parentheses
console.log(r.area()); // TypeError: r.area is not a function
area is computed on every read, but it is read like a stored value. There are no parentheses because there is no call from the caller's point of view.
Why that matters: you can start with a plain property and turn it into a getter later without touching a single line that uses it. The reverse is also true. The caller never has to know which one it is.
// Version 1: stored
class User {
constructor(f, l) {
this.fullName = `${f} ${l}`;
}
}
// Version 2: computed, and every existing `user.fullName` still works
class User {
constructor(f, l) {
this.first = f;
this.last = l;
}
get fullName() {
return `${this.first} ${this.last}`;
}
}
A setter runs on assignment:
class Temperature {
#celsius = 0;
get celsius() {
return this.#celsius;
}
set celsius(value) {
if (typeof value !== "number") throw new TypeError("celsius must be a number");
if (value < -273.15) throw new RangeError("below absolute zero");
this.#celsius = value;
}
get fahrenheit() {
return this.#celsius * 9 / 5 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
}
}
const t = new Temperature();
t.celsius = 25;
console.log(t.fahrenheit); // 77
t.fahrenheit = 212;
console.log(t.celsius); // 100
// t.celsius = -300; // RangeError: below absolute zero
Two views of one stored value, each readable and writable, with validation on the way in. To the caller these are four ordinary properties.
There is a second benefit that is easy to miss. Because both views write to the same private field, the object can never hold a celsius and a fahrenheit reading that disagree with each other. A version that stored both as plain properties would have to keep them in step by hand on every write, and eventually would fail to.
Getters live on the prototype, like any other method:
console.log(Object.getOwnPropertyNames(Temperature.prototype));
// [ 'constructor', 'celsius', 'fahrenheit' ]
const d = Object.getOwnPropertyDescriptor(Temperature.prototype, "celsius");
console.log(typeof d.get, typeof d.set); // function function
console.log(d.value); // undefined: there is no stored value
A getter should be cheap and free of side effects, because it reads like a property and every reader will assume it behaves like one. If computing it is expensive or it changes something, make it a method with parentheses so the cost is visible at the call site.
EXERCISE
2Patterns Worth Knowing
Four shapes cover most of what classes are actually used for in real codebases.
Read-only from outside, writable within:
class Order {
#items = [];
// a copy, not the array itself
get items() {
return [...this.#items];
}
get total() { return this.#items.reduce((s, i) => s + i.price, 0); }
add(item) {
this.#items.push(item);
return this;
}
}
const o = new Order().add({ price: 40 }).add({ price: 60 });
console.log(o.total); // 100
o.items.push({ price: 999 }); // pushes into a copy
console.log(o.total); // 100, unchanged
Returning [...this.#items] is deliberate. Handing out the real array would let any caller modify your internals despite the field being private.
Validation in one place:
class Email {
#value;
constructor(value) {
this.value = value; // goes through the setter
}
get value() {
return this.#value;
}
set value(v) {
if (!v.includes("@")) throw new TypeError(`invalid email: ${v}`);
this.#value = v.trim().toLowerCase();
}
}
console.log(new Email(" Ada@Example.COM ").value); // ada@example.com
The constructor assigns through the setter, so the rule cannot be bypassed at construction time. Normalisation happens once, in the one place that knows about it.
Guarding an invalid state rather than allowing it:
class Range {
#min; #max;
constructor(min, max) {
if (min > max) throw new RangeError("min cannot exceed max");
this.#min = min;
this.#max = max;
}
get min() {
return this.#min;
}
get max() {
return this.#max;
}
contains(n) {
return n >= this.#min && n <= this.#max;
}
}
No setters at all. The object cannot be put into an invalid state after construction, because it cannot be changed after construction. This is the simplest form of immutability and often the right default.
Knowing when a class is the wrong tool:
class MathHelper {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
}
// Nothing here needs an instance, a prototype or `this`.
// Plain exported functions say the same thing with less ceremony:
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
A class earns its place when objects hold state and behaviour together. A class with only static methods is a namespace, and a module already is one.
Pro Tip: The test for whether something should be a class: does it have state that several methods need, and should that state be invalid-proof? If yes, a class with private fields and accessors is exactly right. If the answer is a bag of unrelated helpers, export functions instead and skip the ceremony.
EXERCISE
3Accessors Outside Classes
Getters and setters are a property feature rather than a class feature, and they work on plain objects too.
Nothing about accessors is tied to class. They are a kind of property, so they work anywhere a property does.
In an object literal:
const cart = {
items: [{ price: 40 }, { price: 60 }],
get total() {
return this.items.reduce((sum, i) => sum + i.price, 0);
},
set clear(_) {
this.items = [];
},
};
console.log(cart.total); // 100
cart.clear = true;
console.log(cart.total); // 0
The setter there is a slightly awkward shape, and it illustrates a real guideline: a setter should set something named after itself. cart.clear = true reads as an assignment and behaves as a command, which will surprise the next reader. A method called clear() would have been honest.
Added to an existing object with defineProperty:
const user = { first: "Ada", last: "Lovelace" };
Object.defineProperty(user, "fullName", {
get() {
return `${this.first} ${this.last}`;
},
enumerable: true,
});
console.log(user.fullName); // Ada Lovelace
console.log(Object.keys(user)); // [ 'first', 'last', 'fullName' ]
This is what a class getter compiles down to, with enumerable left false.
And a getter with no setter is silently ignored on write:
const r = {
width: 3,
get area() {
return this.width * 2;
},
};
r.area = 999; // no setter: ignored in sloppy mode
console.log(r.area); // 6
"use strict";
// In strict mode and in modules, the same assignment throws:
// TypeError: Cannot set property area of #<Object> which has only a getter
Worth knowing, because a read-only accessor that silently swallows writes is a confusing bug, and in modules it correctly becomes an error instead.
One thing accessors cannot do: be asynchronous.
const data = {
// get value() { return await fetch(...); } not possible
async getValue() {
return "...";
},
};
There is no async get. A property read has to produce a value immediately, so anything that waits must be a method. That constraint is a useful signal in itself: if fetching the value takes time, the caller deserves to see parentheses.
Accessors are at their best when they present a value the object already has, in a different shape: a total derived from items, a full name from two parts, a duration in different units. When a getter starts doing work the caller would be surprised by, make it a method and let the parentheses warn them.
