JavaScript Getters & Setters

Properties That Run Code

JavaScript Getters & Setters

`get` and `set` create properties backed by functions — they look like data but compute or validate on access.

4 min read Level 2/5 #classes#getters#setters
What you'll learn
  • Define `get` accessors to compute property values
  • Define `set` accessors to validate or transform on assignment
  • Know when getter/setter is the right tool

A getter is a method that’s called when you READ a property. A setter is a method called when you ASSIGN to one. They make properties look like data while running code under the hood.

A getter script.js
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 parens, even though it runs a function
▶ Preview: console

Notice we read r.area, not r.area(). The getter makes it feel like a stored value, but it’s computed on each access.

Setter — Validate or Transform on Write

A setter runs when you assign to the property.

A setter script.js
class Temperature {
  #celsius = 0;

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

  set celsius(value) {
    if (typeof value !== "number") throw new TypeError("number required");
    this.#celsius = value;
  }

  get fahrenheit() {
    return this.#celsius * 9 / 5 + 32;
  }
}

const t = new Temperature();
t.celsius = 100;
console.log(t.celsius);    // 100
console.log(t.fahrenheit); // 212
▶ Preview: console

Setters are good places to put validation — bad input throws right at the boundary instead of corrupting state silently.

Getters on Plain Objects

Getters and setters also work on object literals:

Getter on a plain object script.js
const circle = {
  radius: 5,
  get area() {
    return Math.PI * this.radius ** 2;
  },
};

console.log(circle.area.toFixed(2)); // "78.54"
▶ Preview: console

When to Use a Getter

A getter is appropriate when:

  • The value is derived from other state (area from width × height).
  • You want lazy / on-demand computation.
  • You want a stable property name while changing the underlying storage later.

A getter is not appropriate when:

  • The computation is expensive — callers expect a property read to be fast.
  • There’s I/O or async work involved. Use a method.

When to Use a Setter

  • Input validation at the boundary.
  • Keeping derived state in sync.
  • Logging / change detection.

Use setters sparingly — they can hide work behind a simple assignment.

Up Next

A primitive type built for unique keys.

JavaScript Symbols →