Glossary / Getters and setters

Getters and setters

Getters and setters are accessor properties that run functions when a property is read or assigned. They can expose derived values, validate or normalize writes, and preserve an API while changing internal representation. Their syntax looks like ordinary property access, so hidden computation and side effects can surprise consumers.

Defining and using accessors

const person = {
  first: "Ada",
  last: "Lovelace",
  get fullName() { return `${this.first} ${this.last}`; },
  set fullName(value) {
    [this.first, this.last] = value.split(" ");
  },
};

An accessor descriptor has get and/or set, not value/writable. A getter takes no arguments; a setter takes one value. Getter this follows ordinary method receiver rules. Inherited getters may therefore read child-instance state. A setter may reject a value by throwing or normalize it; its assignment expression still evaluates to the right-hand value, not a value returned by the setter.

Property access can invoke getters during logging, object spread, serialization, and framework inspection. Keep getters fast, deterministic, and side-effect-free; do not start asynchronous work from them. A getter that reads and writes the same property can recurse infinitely. Use methods when work is expensive, asynchronous, or action-like.

Interview questions

  1. Can a getter accept parameters? No; a getter is read as a property and has no arguments.
  2. What is the difference between a data and accessor descriptor? Stored value/writability versus get/set functions.
  3. Can object spread invoke a getter? Yes, it reads enumerable own properties to copy their values.
  4. When should a method be used instead? For expensive, asynchronous, or effectful operations that should look like actions.

References