← Back to JavaScript, page 8

javascript-0142 · Medium mid

How do you implement a lazily computed property with a getter that runs once and then caches its value?

Define a getter that computes the value on first access, then replaces itself with a plain data property using Object.defineProperty (or stores the result in a private field or with ??=), so later reads are simple property reads. It saves work for values that are expensive and often not needed. Be careful with values that can change, with null results, and with inheritance.

Full answer

A lazy property postpones an expensive computation until the first time it is read. If it is never read, it never runs.

Pattern 1, self-replacing getter: the getter computes the value, then calls Object.defineProperty(this, 'name', { value, writable: false, enumerable: true, configurable: true }). That shadows the getter on the instance with a data property, so the next reads do not call any function. This is fast after the first access, and it does not need a separate cache field. It only works when the getter is defined on the prototype (a class getter) or on the object itself with configurable: true.

Pattern 2, cached field in the class: store the result in a private field and use the nullish assignment: get report() { return this.#report ??= buildReport(this.data); }. It is short and readable, and the cache stays private. Note that ??= recomputes when the cached value is null or undefined. Use a flag or a Symbol sentinel if those are valid results.

Pattern 3, a reusable helper: lazy(obj, key, factory) defines a getter on the object that calls the factory once, then redefines the property as a data property. It can be used on object literals, or for module-level configuration.

Things to watch:

  • Invalidation: a lazy value is computed once. If the inputs change later, the value is stale. Either make the object immutable, or provide a method to reset the cache.
  • Errors: if the factory throws, nothing is cached, and the next access tries again, which is usually what you want. State it clearly.
  • Inheritance and this: a getter defined on a prototype is shared, but the cached value must be stored per instance (use this, not the prototype).
  • Serialization: a self-replacing getter becomes an own enumerable property after the first read, so JSON.stringify results can change depending on whether it was read. Make it non-enumerable if that matters.
  • Async: for async values, cache the promise, not the resolved value.

Use lazy properties for expensive parsing, large derived data, and optional features. Do not use them to hide slow code on a hot path without measuring.

javascript
const log = [];
const expensive = (label) => {
  log.push('computing ' + label);
  return label.toUpperCase();
};

// Pattern 1: self-replacing getter on the prototype
class Report {
  constructor(title) {
    this.title = title;
  }
  get summary() {
    const value = expensive('summary of ' + this.title);
    Object.defineProperty(this, 'summary', { value, enumerable: false, configurable: true });
    return value;
  }
}
const report = new Report('q4');
console.log('keys before:', Object.keys(report));
console.log(report.summary, report.summary, report.summary);
console.log('computed times:', log.length, '| own property now:', Object.hasOwn(report, 'summary'), '| keys:', Object.keys(report));
console.log('another instance is separate:', new Report('q1').summary, log.length);

// Pattern 2: private field with ??=
class Config {
  #parsed;
  constructor(text) {
    this.text = text;
  }
  get parsed() {
    return (this.#parsed ??= JSON.parse(this.text));
  }
  reset() {
    this.#parsed = undefined;
  }
}
const config = new Config('{"retries":3}');
console.log(config.parsed === config.parsed, config.parsed);
const broken = new Config('{bad json');
for (let attempt = 1; attempt <= 2; attempt++) {
  try {
    broken.parsed;
  } catch (error) {
    console.log('attempt', attempt, 'failed again:', error.name);
  }
}

// null results with ??= are recomputed, a sentinel fixes that
let calls = 0;
const nullable = { _v: undefined, get value() { calls++; return (this._v ??= null); } };
nullable.value; nullable.value;
console.log('null is not cached by ??=, calls:', calls);

// Pattern 3: a reusable helper
function lazy(object, key, factory) {
  Object.defineProperty(object, key, {
    configurable: true,
    enumerable: true,
    get() {
      const value = factory.call(this);
      Object.defineProperty(this, key, { value, enumerable: true, configurable: true, writable: true });
      return value;
    },
  });
  return object;
}
log.length = 0;
const settings = lazy({ name: 'app' }, 'cache', () => expensive('cache for app'));
console.log(log.length, settings.cache, settings.cache, log.length, JSON.stringify(settings));

// async: cache the promise
const lazyUser = { get user() { const p = Promise.resolve({ id: 1 }); Object.defineProperty(this, 'user', { value: p }); return p; } };
console.log('same promise returned:', lazyUser.user === lazyUser.user);

Run with Node.js v24.22.1 as js-142.js; two runs gave identical output. Output: keys before: [ 'title' ] SUMMARY OF Q4 SUMMARY OF Q4 SUMMARY OF Q4 computed times: 1 | own property now: true | keys: [ 'title' ] another instance is separate: SUMMARY OF Q1 2 true { retries: 3 } attempt 1 failed again: SyntaxError attempt 2 failed again: SyntaxError null is not cached by ??=, calls: 2 0 CACHE FOR APP CACHE FOR APP 1 {"name":"app","cache":"CACHE FOR APP"} same promise returned: true

Key points

  • A lazy getter computes on first read and never again; unread values cost nothing.
  • Self-replacing: defineProperty on the instance turns the getter into a data property.
  • Cached private field with ??= is short, but null or undefined results recompute.
  • Watch for stale values, errors that are not cached, and enumerable properties changing JSON output.
  • For async values, cache the promise.

Common mistakes

  • Caching a value that depends on data that can change later.
  • Using ??= when null or undefined are valid results.
  • Storing the cache on the prototype so all instances share one value.
  • Making lazy properties enumerable and getting different JSON depending on read order.

Follow-ups

  • How would you reset a self-replacing getter?
  • How does lazy initialization differ from memoizing a function?
  • Why cache the promise instead of the resolved value for async data?

Tips

  • Show the self-replacing getter and the ??= field as the two main patterns.
  • Mention stale values and errors explicitly.
  • Say that you measure before adding laziness.