Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 156 ยท Objects

Getters and Setters

Create properties that run code when read or written. Learn get and set in objects and classes, computed values, validation and Object.defineProperty.

Most properties simply store a value. You write box.width = 10 and later read box.width back. Accessor properties look exactly the same from the outside, but behind them sit two functions: a getter that runs when the property is read and a setter that runs when it is assigned.

That lets an object compute a value on demand (a fullName built from first and last names), check new values before accepting them (no negative prices), or react to a change (log it, update something else), while the code using the object keeps the simple obj.prop syntax. This lesson shows how to write getters and setters in object literals and classes, the patterns they are good for, and a few traps to avoid.

Your first getter

Put the keyword get in front of a method, and that method becomes a property. Reading the property calls the method and gives you its return value:

JS A computed property

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You read person.fullName with no (), just like a normal property. The getter runs fresh every time, so the value is always in sync with firstName and lastName. If you stored the full name as an ordinary property instead, you would have to remember to update it whenever either part changed.

Inside a getter, this is the object the property was read from, just like in a regular method. (See The this Keyword for the full story.)

A getter takes no parameters and should return something. If it has no return, reading the property gives undefined.

Adding a setter

A setter uses the keyword set and receives exactly one parameter: the value being assigned. Pair it with a getter of the same name to make a read-write property:

JS Getter and setter pair

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Assigning person.fullName = "โ€ฆ" calls the setter with the string. The setter splits it up and stores the parts in the real data properties. The setter's return value is ignored; the assignment expression always evaluates to the value on its right.

If an object has a getter but no setter, the property is read-only. Assigning to it does nothing in sloppy mode and throws a TypeError in strict mode, which includes classes and modules. A setter without a getter is legal but odd: reading the property gives undefined.

Validation with a backing property

A getter and setter can't store a value under their own name. If the setter did this.price = value, it would call itself again, forever. Instead, keep the real value in a separate backing property. A leading underscore is the traditional hint that it is internal:

JS Validating a value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Every assignment now goes through one checkpoint. Bad values never get in, and good values are normalized (rounded to cents). You'll learn more about throwing errors in Throwing and Custom Errors.

The underscore is only a convention, though. Nothing stops other code from writing product._price = -100 directly. Classes have a real fix for that, which you'll see next.

Infinite recursion. Inside set price(value), writing this.price = value calls the same setter again, which calls it again, until the engine stops with RangeError: Maximum call stack size exceeded. Always store into a different property.

Getters and setters in classes

Classes use the same get and set keywords. Combined with private fields (names starting with #), the backing value becomes truly hidden. You'll study classes and private fields properly later, but the pattern is easy to read already:

JS Accessors in a class

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The class stores one real value, #celsius, and exposes two views of it. Notice how the fahrenheit setter assigns to this.celsius rather than this.#celsius, so it goes through the same validation. Keeping a single source of truth and deriving everything else is one of the best uses of accessors.

In a class, accessors live on the prototype, shared by every instance, just like methods. That's why Object.keys(room) doesn't list them.

Defining accessors with Object.defineProperty

You can also add an accessor to an existing object with Object.defineProperty(). You pass get and/or set functions in a descriptor object:

JavaScript
const counter = { clicks: 0 };

Object.defineProperty(counter, "label", {
  get() {
    return `${this.clicks} click${this.clicks === 1 ? "" : "s"}`;
  },
  enumerable: true,
});

counter.clicks = 3;
console.log(counter.label); // "3 clicks"

Unlike the literal syntax, properties created with defineProperty default to non-enumerable and non-configurable, so they are hidden from Object.keys() and can't be deleted unless you set those flags to true. You can inspect any property with Object.getOwnPropertyDescriptor(obj, "name"): a data property shows value and writable, an accessor shows get and set.

Accessors and copying

Getters behave differently from data properties when you copy or serialize an object. Object spread, Object.assign() and JSON.stringify() all read the property, which runs the getter, and then store the result as a plain value:

JS Copies freeze the current value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The original has get and set in its descriptor; the copy has a fixed value. That's usually what you want for a snapshot, but it surprises people who expect the copy to stay "live".

When to use getters and setters

Accessors are a good fit when:

  • A value is derived from other data and should never go stale: totals, full names, areas, counts, formatted labels.
  • Assignments need validation or normalization: ranges, types, trimming, rounding.
  • You need a read-only view of internal state, for example a getter with no setter over a private field.
  • Changing a value should trigger a side effect, such as re-rendering. Keep these light and predictable.

Avoid them when the work is slow or surprising. Readers expect obj.prop to be cheap and to return the same thing twice in a row. A getter that hits the network, takes a long time or changes state on every read is better written as a method with a verb in its name, such as loadUser() or calculateReport(), so the cost is visible at the call site.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An object has get area() { return this.w * this.h; }. How do you read the area?

    A getter is read like a normal property, with no parentheses. Calling obj.area() would try to call the returned number.
  2. 2. What goes wrong in set name(v) { this.name = v; }?

    this.name = v triggers the same setter. Store the value in a separate backing property such as _name or #name.
  3. 3. A property has a getter but no setter. What happens when strict-mode code assigns to it?

    Without a setter the property is read-only. Strict mode (including classes and modules) throws; sloppy mode silently ignores the assignment.
  4. 4. What does { ...obj } do with a getter on obj?

    Spread reads each property, so the getter runs once and the copy gets a fixed data property.
  5. 5. Which is the better candidate for a method instead of a getter?

    Property reads should be cheap and side-effect free. Slow work like network access belongs in a method such as loadLatestPrices().

Summary

  • A getter (get prop() {}) runs when the property is read; a setter (set prop(value) {}) runs when it is assigned.
  • Callers use plain obj.prop syntax, with no parentheses.
  • Getters are ideal for derived values that must stay in sync; setters for validation and normalization.
  • Store the real value in a separate backing property (_value by convention, #value in classes) to avoid infinite recursion.
  • A getter without a setter makes a read-only property; assigning to it throws in strict code.
  • Spread, Object.assign() and JSON.stringify() run getters and keep only the current value.
  • Keep accessors fast and free of surprises; use methods for slow or state-changing work.

Next: JSON โ€” turning objects into text and back again.