Sub topic 6
Validating and Computing Values Through Accessors
This chapter assumes you can already write class getters and setters and declare private fields with #. Both were covered in earlier chapters. Here we use them together for real work. Setters guard the values a class stores, and getters derive new values from that stored state.
You will learn how to reject bad input, normalize good input, expose computed properties, keep several fields consistent with each other, and cache expensive derived values without letting them go stale.
The Guarded-Field Pattern
Most validated properties follow the same shape:
- A private field holds the real value.
- A public getter returns it, or a safe copy of it.
- A public setter checks the incoming value, normalizes it, and only then writes the private field.
- The constructor assigns through the setter, so new instances get the same checks.
Here is the pattern applied to a product with a name and a price:
class Product {
#name;
#price;
constructor(name, price) {
this.name = name; // runs the name setter
this.price = price; // runs the price setter
}
get name() {
return this.#name;
}
set name(value) {
if (typeof value !== 'string') {
throw new TypeError('name must be a string');
}
const trimmed = value.trim();
if (trimmed === '') {
throw new RangeError('name must not be empty');
}
this.#name = trimmed;
}
get price() {
return this.#price;
}
set price(value) {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new TypeError('price must be a finite number');
}
if (value < 0) {
throw new RangeError('price must not be negative');
}
this.#price = Math.round(value * 100) / 100;
}
}
const p = new Product(' Desk Lamp ', 19.999);
console.log(p.name); // 'Desk Lamp'
console.log(p.price); // 20
try {
p.price = NaN;
} catch (err) {
console.log(err.name, err.message); // TypeError price must be a finite number
}
try {
p.price = -5;
} catch (err) {
console.log(err.name, err.message); // RangeError price must not be negative
}
console.log(p.price); // 20 (the failed assignments changed nothing)Look at the order of operations. Every check runs before the private field is written. When a check fails, the object keeps its last valid state, so a caller who catches the error still holds a usable object.
Why `Number.isFinite` and not `typeof`
typeof NaN and typeof Infinity are both 'number', so a typeof check alone lets them through. Number.isFinite(value) returns false for NaN, Infinity, -Infinity, and every non-number, and it does not coerce its argument. The global isFinite('5') returns true because it converts the string first. Use the Number. version in validators.
TypeError vs RangeError
Use the built-in error types the way the language does. A TypeError means the value is the wrong kind of thing. A RangeError means the kind is right but the value is outside the allowed limits. Callers can then branch on err instanceof RangeError without parsing message strings.
Choosing a Strategy for Bad Input
Throwing is only one option. The right choice depends on who supplies the value and what a wrong value costs.
| Strategy | Example | When it fits | Risk |
|---|---|---|---|
| Throw | `throw new RangeError(...)` | Programmer errors, data that must be correct | Callers must handle exceptions |
| Coerce | `this.#qty = Number(value)` | Loose input such as form fields | `Number('abc')` gives `NaN`, so check it afterward |
| Clamp | `Math.min(100, Math.max(0, v))` | UI values like volume or opacity | Hides caller mistakes |
| Ignore | `if (!ok) return;` | Almost never | Silent data loss, very hard to debug |
Normalization is a separate concern from rejection. You can accept a value and still change its form: trim whitespace, lowercase an email, round currency to cents, or copy a Date so the caller cannot mutate it later. Do normalization after validation, so you are never normalizing garbage.
Computed Properties
A computed property is a getter that derives its value from other state instead of storing it. It can never go out of date, because nothing is stored that could drift.
'use strict';
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
get isSquare() {
return this.width === this.height;
}
}
const r = new Rectangle(3, 4);
console.log(r.area); // 12
r.width = 5;
console.log(r.area); // 20
console.log(r.isSquare); // false
try {
r.area = 100; // getter with no setter
} catch (err) {
console.log(err instanceof TypeError); // true
}area has no setter, so it is read-only. Watch which mode applies here. A class body is always strict mode, but what decides the outcome is the mode of the code doing the assignment. In strict code, assigning to a getter-only property throws a TypeError. In a sloppy-mode script, the same assignment fails silently and r.area stays 20. ES modules are always strict, so in modern code the throw is what you will usually see.
Computed Properties You Can Write To
A computed property can also have a setter that does the reverse: it breaks the input apart and updates the underlying fields.
class Person {
#first;
#last;
constructor(fullName) {
this.fullName = fullName;
}
get fullName() {
return `${this.#first} ${this.#last}`;
}
set fullName(value) {
if (typeof value !== 'string') {
throw new TypeError('fullName must be a string');
}
const parts = value.trim().split(/\s+/);
if (parts.length < 2) {
throw new RangeError('Expected a first and last name');
}
this.#first = parts[0];
this.#last = parts.slice(1).join(' ');
}
get initials() {
return `${this.#first[0]}${this.#last[0]}`.toUpperCase();
}
}
const ada = new Person('Ada King Lovelace');
console.log(ada.fullName); // 'Ada King Lovelace'
console.log(ada.initials); // 'AK'
ada.fullName = 'Grace Hopper';
console.log(ada.initials); // 'GH'Notice the round trip. Input 'Ada King Lovelace' comes back as 'Ada King Lovelace'. Because of normalization, reading a property right after writing it may not return exactly what you wrote. That is usually what you want, but document it so callers are not surprised.
Keeping Several Fields Consistent
Per-field setters only see one value at a time. Some rules involve two fields at once, such as "start must not be after end". If each setter checks against the current value of the other field, moving a range forward in time can fail partway: setting the new start first puts it after the old end.
The fix is to put the rule in one method that validates both values together. The individual setters then delegate to it.
function toDate(value) {
const d = value instanceof Date ? new Date(value.getTime()) : new Date(value);
if (Number.isNaN(d.getTime())) {
throw new TypeError(`Invalid date: ${value}`);
}
return d;
}
class DateRange {
#start;
#end;
constructor(start, end) {
this.setRange(start, end);
}
get start() {
return new Date(this.#start.getTime()); // defensive copy
}
set start(value) {
this.setRange(value, this.#end);
}
get end() {
return new Date(this.#end.getTime());
}
set end(value) {
this.setRange(this.#start, value);
}
get days() {
return Math.round((this.#end - this.#start) / 86_400_000);
}
setRange(start, end) {
const s = toDate(start);
const e = toDate(end);
if (s > e) {
throw new RangeError('start must not be after end');
}
this.#start = s; // both writes happen only after all checks pass
this.#end = e;
}
}
const range = new DateRange('2026-01-01', '2026-01-10');
console.log(range.days); // 9
try {
range.start = '2026-02-01'; // would be after the current end
} catch (err) {
console.log(err.message); // 'start must not be after end'
}
range.setRange('2026-02-01', '2026-02-15');
console.log(range.days); // 14
range.start.setFullYear(1999); // changes only the returned copy
console.log(range.start.getFullYear()); // 2026This example shows two more habits.
- Defensive copies.
Dateobjects, arrays, and plain objects are mutable. If a getter returns the private object itself, a caller can change it in place and bypass every check. Return a copy, or freeze the value before storing it. The same applies on input:toDatecopies an incomingDateso the caller's later changes cannot reach the stored value. - Validate everything, then write everything.
setRangewrites neither field until both have passed. A failure therefore never leaves the object half-updated.
Caching Expensive Computed Values
A getter looks like a cheap field read, and callers will treat it that way. They will call it inside loops and render functions. If computing the value is expensive, cache it, and have every setter that affects the result clear the cache.
class TextStats {
#text = '';
#wordCount = null; // null means "not computed yet"
constructor(text) {
this.text = text;
}
get text() {
return this.#text;
}
set text(value) {
if (typeof value !== 'string') {
throw new TypeError('text must be a string');
}
this.#text = value;
this.#wordCount = null; // invalidate the cache
}
get wordCount() {
if (this.#wordCount === null) {
const trimmed = this.#text.trim();
this.#wordCount = trimmed === '' ? 0 : trimmed.split(/\s+/).length;
}
return this.#wordCount;
}
}
const stats = new TextStats('the quick brown fox');
console.log(stats.wordCount); // 4 (computed)
console.log(stats.wordCount); // 4 (cached)
stats.text = 'hello world';
console.log(stats.wordCount); // 2 (recomputed after invalidation)Caching works only while every write goes through a setter that clears the cache. Private fields make that a guarantee, because no outside code can change #text directly. With a public text field, any direct assignment would leave wordCount stale.
Common Errors at a Glance
| Mistake | Symptom | Fix |
|---|---|---|
| Constructor writes `#field` directly | Invalid objects at creation time | Assign through the setter |
| Using `typeof` alone for numbers | `NaN` and `Infinity` accepted | Add `Number.isFinite` |
| Writing a field before all checks | Half-updated object after an error | Validate first, write last |
| Getter returns an internal array or `Date` | Outside code mutates state | Return a copy |
| Cache not cleared in one setter | Stale computed value | Invalidate in every setter that affects the result |
| Expensive getter without a cache | Slow loops and renders | Cache it, or make it an explicit method like `computeTotal()` |
Exercise
A Volume class has a level setter that should accept numbers, clamp them to the range 0–100, and reject anything that is not a finite number with a TypeError. Write the class using a private #level field, with the constructor going through the setter. What do new Volume(150).level and new Volume(-3).level return?
Show answer
class Volume { #level; constructor(level) { this.level = level; } get level() { return this.#level; } set level(v) { if (typeof v !== 'number' || !Number.isFinite(v)) throw new TypeError('level must be a finite number'); this.#level = Math.min(100, Math.max(0, v)); } } — new Volume(150).level returns 100 and new Volume(-3).level returns 0. new Volume(NaN) throws a TypeError, because the type check runs before clamping.
Exercise
A Cart class stores items in a private #items array and has get items() { return this.#items; } plus a cached total getter that is cleared inside addItem(). A user runs cart.items.push({ price: 50 }) and then reads cart.total. What goes wrong, and how do you fix it?
Show answer
The getter returns the real private array, so push changes internal state without going through addItem(). The cache is never cleared, and total returns a stale value that leaves out the new item. Fix it by returning a copy (return [...this.#items];) or a frozen copy (Object.freeze([...this.#items])), so the only way to change the items is through methods that clear the cache.
Exercise
In the DateRange example, why do the start and end setters call setRange instead of each checking only their own value against the other field?
Show answer
The rule "start must not be after end" involves both fields. If each setter checked against the current value of the other field, some valid changes would fail partway, such as moving a whole range later by setting start first. Sending both setters through setRange keeps the rule in one place, checks both values together, and writes neither field until both pass, so the object is never left half-updated.