Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Classes and Modules

Getters and setters in classes

Reference for JavaScript get and set accessors in classes and objects: computed properties, validation, read-only values, static and private accessors.

An accessor property looks like a normal property but runs a function when you read it (get) or assign to it (set). Use accessors to compute values on demand, to validate or normalize input, or to expose a read-only view of private state while keeping the same simple obj.name syntax.

JavaScript
class Temperature {
  #celsius = 0;
  get fahrenheit() { return this.#celsius * 9 / 5 + 32; }
  set fahrenheit(value) { this.#celsius = (value - 32) * 5 / 9; }
}

Try it

JS Computed and validated properties

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

No output.

JS Object literals, static and defineProperty

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

No output.

Syntax

JavaScript
class Name {
  get prop() { return value; }
  set prop(newValue) { /* ... */ }

  static get shared() { /* ... */ }
  get #secret() { /* ... */ }
  get [computedName]() { /* ... */ }
}

const obj = {
  get prop() { return value; },
  set prop(v) { /* ... */ },
};
  • A getter takes no parameters and returns the value of the property.
  • A setter takes exactly one parameter; its return value is ignored.
  • You can define just one of the two. Only a getter makes the property read-only; only a setter makes it write-only (reads give undefined).

Usage notes

  • Where they live. In a class, accessors are defined on the prototype (not enumerable), so they do not appear in Object.keys(), spread or JSON.stringify(). In an object literal they are own, enumerable properties and JSON.stringify() calls the getter.
  • Assigning without a setter. In strict mode, and therefore inside any class body and in modules, writing to a getter-only property throws TypeError. In sloppy-mode scripts the assignment is silently ignored.
  • Same name as a field. A getter and a field with the same name conflict. The usual pattern is a private field #value plus a public accessor value.
  • Cost. An accessor runs code every time. Cache expensive results yourself, and avoid getters with surprising side effects.
  • Inheritance. A subclass that defines only a getter for a name also removes the parent's setter for it; define both when overriding.
  • Static and private accessors are allowed: static get, get #x.
  • Not for methods. Do not use a getter to return a function that does work; a plain method says what it does.
  • Descriptors. Object.defineProperty() takes get/set for the same purpose.

Browser support

Accessors have worked in all browsers for a long time. Static and private accessors are newer but supported in current browsers; check a compatibility table for old targets.