typestar

Getters and setters in JavaScript

Computed properties that look like plain fields.

class Run {
  #tpm = 0;

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

  set tpm(value) {
    if (value < 0) throw new RangeError("tpm cannot be negative");
    this.#tpm = value;
  }

  get stars() {
    return this.#tpm >= 100 ? 3 : 1;
  }
}

const run = new Run();
run.tpm = 104;
console.log(run.tpm, run.stars);

try {
  run.tpm = -1;
} catch (error) {
  console.log(error.name);
}

const frozen = {};
Object.defineProperty(frozen, "id", { get: () => "fixed", enumerable: true });
console.log(frozen.id, Object.keys(frozen));

How it works

  1. A getter runs on read, a setter validates on write.
  2. defineProperty sets them on an existing object.
  3. Keep them cheap: callers expect a field, not a query.

Keywords and builtins used here

The run, in numbers

Lines
30
Characters to type
490
Tokens
158
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 86 seconds.

Type this snippet

Step 3 of 4 in Objects under the hood, step 14 of 16 in Functions & patterns.

← Previous Next →