Skip to content
jshacks.dev
Fundamentals

Getters and Setters in JavaScript Objects and Classes

A getter runs code when a property is read and a setter when it is written. See validation, lazy caching and why a class getter vanishes from JSON.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, npm and Vite logos.

A getter makes a computed value look like a stored one. invoice.total reads like a field and calculates from the line items each time, user.fullName assembles two names, and account.balance = -5 can reject the assignment. Used well, that keeps a public surface simple and the data consistent. Used carelessly, it hides work behind what looks like a property read, and breaks serialization in ways that surprise. This post covers the syntax in objects and classes, the read-only case, validation, caching and the serialization trap, with output from Node.js 24. The mechanism underneath is in the post on property descriptors, and class syntax is explained in the post on classes.

The syntax

In an object literal, get and set before a method name define an accessor.

JavaScript
const person = {
  first: "Ada",
  last: "Lovelace",

  get fullName() {
    return this.first + " " + this.last;
  },

  set fullName(value) {
    [this.first, this.last] = value.split(" ");
  },
};

console.log(person.fullName);

person.fullName = "Grace Hopper";
console.log(person.first, person.last);
console.log(person.fullName);
Text
Ada Lovelace
Grace Hopper
Grace Hopper

Reading fullName called the getter, and assigning to it called the setter, which split the string and wrote two real properties. The caller never wrote a parenthesis. The property has no stored value of its own: it is derived from first and last, so it can never be out of date.

A getter with no setter is read-only

If only the getter exists, the property can be read and not written.

JavaScript
const order = {
  price: 20,
  quantity: 3,
  get total() {
    return this.price * this.quantity;
  },
};

console.log(order.total);

try {
  order.total = 100;
} catch (error) {
  console.log(error.name + ": " + error.message);
}

console.log(order.total);
Text
60
TypeError: Cannot set property total of #<Object> which has only a getter
60

In an ES module, which is strict, the write threw a TypeError with a message naming the cause. In sloppy mode the write is silently ignored, which is a bad outcome for a bug, so the strict behavior is the one to depend on. A derived value that should never be set by a caller is the best use of a getter-only property, since the type signature and the runtime agree.

Validation in a setter

A setter is a gate. It can reject or normalize an assignment before it reaches the stored value. The stored value needs a different name from the property, because assigning to the same name from inside the setter calls the setter again.

JavaScript
class Account {
  #balance = 0;

  get balance() {
    return this.#balance;
  }

  set balance(value) {
    if (!Number.isFinite(value) || value < 0) {
      throw new RangeError("balance must be a non-negative number");
    }
    this.#balance = value;
  }
}

const account = new Account();
account.balance = 50;
console.log(account.balance);

try {
  account.balance = -5;
} catch (error) {
  console.log(error.name + ": " + error.message);
}

console.log(account.balance);
Text
50
RangeError: balance must be a non-negative number
50

The private field #balance holds the value, and the accessor is the only way in. A rejected assignment left the old value untouched. The post on private class fields covers the # syntax.

The recursion mistake is worth seeing once.

JavaScript
const broken = {
  set name(value) {
    this.name = value;
  },
};

try {
  broken.name = "x";
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
RangeError: Maximum call stack size exceeded

The setter assigned to this.name, which invoked the setter again, until the call stack ran out. The fix is a differently named backing field, _name by convention or #name for a real private one.

Computed values and lazy caching

A getter recomputes on every read. For something expensive, the usual pattern is to compute once and replace the accessor with a plain value.

JavaScript
class Report {
  constructor(rows) {
    this.rows = rows;
  }

  get summary() {
    console.log("computing...");
    const total = this.rows.reduce((sum, value) => sum + value, 0);
    Object.defineProperty(this, "summary", {
      value: { count: this.rows.length, total },
      enumerable: true,
    });
    return this.summary;
  }
}

const report = new Report([5, 10, 15]);

console.log(report.summary);
console.log(report.summary);
console.log(Object.getOwnPropertyDescriptor(report, "summary").value.total);
Text
computing...
{ count: 3, total: 30 }
{ count: 3, total: 30 }
30

"computing..." printed once. On the first read the getter ran, defined an own data property named summary on the instance, which shadows the prototype's getter, and returned it. Later reads find the data property directly. The trade-off is that the cached value goes stale if rows changes, so this suits immutable inputs.

Getters in JSON, spread and iteration

Where a getter is defined decides whether copying and serialization see it. A getter in an object literal is an own enumerable property. A getter in a class lives on the prototype, which JSON.stringify() and spread do not read.

JavaScript
const literal = {
  first: "Ada",
  get shout() {
    return this.first.toUpperCase();
  },
};

class Person {
  constructor(first) {
    this.first = first;
  }
  get shout() {
    return this.first.toUpperCase();
  }
}

const instance = new Person("Ada");

console.log(JSON.stringify(literal));
console.log(JSON.stringify(instance));
console.log({ ...literal });
console.log({ ...instance });
console.log(instance.shout);
console.log(Object.keys(instance));
Text
{"first":"Ada","shout":"ADA"}
{"first":"Ada"}
{ first: 'Ada', shout: 'ADA' }
{ first: 'Ada' }
ADA
[ 'first' ]

The literal's getter appears in the JSON and in the spread, as a plain value captured at that moment. The class getter is missing from both, though instance.shout still works. This is a frequent bug: an API response built with JSON.stringify(model) quietly lacks every computed field defined as a class getter. Fix it with a toJSON() method that returns the shape you want, or build the response object explicitly.

JavaScript
class Person {
  constructor(first) {
    this.first = first;
  }
  get shout() {
    return this.first.toUpperCase();
  }
  toJSON() {
    return { first: this.first, shout: this.shout };
  }
}

console.log(JSON.stringify(new Person("Ada")));
Text
{"first":"Ada","shout":"ADA"}

Defining accessors dynamically

Object.defineProperty() can attach a getter and setter to an existing object, and Object.getOwnPropertyDescriptor() shows them.

JavaScript
const settings = {};
let stored = "light";

Object.defineProperty(settings, "theme", {
  get() {
    return stored;
  },
  set(value) {
    stored = value;
  },
  enumerable: true,
  configurable: true,
});

settings.theme = "dark";
console.log(settings.theme, stored);

const descriptor = Object.getOwnPropertyDescriptor(settings, "theme");
console.log(typeof descriptor.get, typeof descriptor.set, descriptor.value);
Text
dark dark
function function undefined

The accessor reads and writes a variable captured from the outer scope, so the object has no storage of its own. This is the shape libraries use to wrap a value with change tracking, and it is the foundation that some reactivity systems used before proxies.

Static and inherited accessors

Accessors work on static members and are inherited like methods, with one subtlety: a subclass that defines only a setter for a property whose getter lives in the parent hides the parent's getter, because the pair is one property. Define both in the subclass, or neither.

JavaScript
class Shape {
  get label() {
    return "shape";
  }
  set label(value) {
    this._label = value;
  }
}

class Circle extends Shape {
  set label(value) {
    this._label = "circle:" + value;
  }
}

const circle = new Circle();
circle.label = "unit";

console.log(circle._label);
console.log(circle.label);
console.log(new Shape().label);
Text
circle:unit
undefined
shape

The subclass setter ran, but reading label returned undefined, because the subclass's accessor property has a setter and no getter, and it replaces the parent's whole accessor. Nothing warns you about it. The fix is to write both halves in the subclass and delegate with super.label, a pattern that is easy to get wrong and worth a test.

Testing accessors

An accessor is a contract about reading and writing, and the tests that matter check the edges: the rejected value, the derived value after a dependency changes and the behavior of a read-only property. A short node:test file covers all three.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

class Cart {
  #items = [];
  add(price) {
    this.#items.push(price);
  }
  get total() {
    return this.#items.reduce((sum, price) => sum + price, 0);
  }
}

test("total follows the items", () => {
  const cart = new Cart();
  cart.add(5);
  cart.add(7);
  assert.equal(cart.total, 12);
});

test("total cannot be assigned", () => {
  const cart = new Cart();
  assert.throws(() => {
    cart.total = 1;
  }, TypeError);
});

Run it with node --test on Node.js 24. The second test relies on strict mode, which class bodies always have, so the assignment throws and the assertion passes. Without such a test, a later change that adds a setter for convenience would go unnoticed, and the derived value could be overwritten.

When to use a method instead

A getter promises something a method does not: that reading is cheap, repeatable and free of side effects. If any of those is false, make it a method. A property that calls a network, takes a lock or returns a different object each time will surprise a caller who treats it as a field, such as one logging it in a debugger, which runs the getter.

Prefer getTotal() over get total() when the work is heavy, and prefer a plain property when no computation or validation is needed. In TypeScript, a getter and setter pair with unrelated types are allowed since version 5.1, but two types that differ widely are a hint to use two names.

Where accessors fall short

Accessors do not work with Object.assign in the way people expect: the getter is evaluated and the value is copied. They also interact badly with deep clone helpers that use JSON, as shown. And a debugger that shows an object's properties may call every getter, so an expensive or throwing one makes inspection painful.

The syntax is defined in the specification under method definitions, and MDN's pages on getters and setters list the edge cases.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.