Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Read-only computed property in JavaScript

75 A computed property that cannot be assigned

hard

Give an order a total that is computed from its items, refuses assignment, and stays out of Object.keys and JSON.stringify. Then make the same thing enumerable and compare. Contrast it with a non-writable data property, which also refuses assignment but never recomputes, and find the descriptor the engine rejects outright.

Stuck? Three hints, smallest first
  1. 1. A getter with no setter is the read-only part. The attributes control the visibility.
  2. 2. Assigning to an accessor with no setter throws in strict mode.
  3. 3. A descriptor cannot describe both an accessor and a value. Try it and read the error.

The answer

const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };

const order = { items: [{ naira: 25000 }, { naira: 20000 }] };
Object.defineProperty(order, 'total', {
  get() { return this.items.reduce((sum, item) => sum + item.naira, 0); },
  enumerable: false,
  configurable: true,
});

const computed = order.total;
order.items.push({ naira: 5000 });
const recomputed = order.total;

const assignRefused = attemptName(() => { order.total = 1; });
const hidden = [Object.keys(order), JSON.stringify(order), Object.hasOwn(order, 'total')];
const spreadDropsIt = Object.keys({ ...order });

Object.defineProperty(order, 'total', {
  get() { return this.items.reduce((sum, item) => sum + item.naira, 0); },
  enumerable: true,
  configurable: true,
});
const nowVisible = [Object.keys(order), JSON.parse(JSON.stringify(order)).total];

// A non-writable data property: also refuses assignment, and never recomputes.
const snapshot = { items: order.items };
Object.defineProperty(snapshot, 'total', { value: 50000, writable: false, enumerable: true });
const dataRefused = attemptName(() => { snapshot.total = 1; });
snapshot.items.push({ naira: 100000 });
const staleTotal = snapshot.total;
const liveTotal = order.total;

const bothAtOnce = attemptName(() => Object.defineProperty({}, 'total', { value: 1, get() { return 2; } }));
const kinds = [
  typeof Object.getOwnPropertyDescriptor(order, 'total').get,
  'writable' in Object.getOwnPropertyDescriptor(order, 'total'),
  typeof Object.getOwnPropertyDescriptor(snapshot, 'total').get,
];

console.log('computed, recomputed:', computed, recomputed);
console.log('hidden              :', hidden);
console.log('stale vs live       :', staleTotal, liveTotal);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the getter computes from the items', computed, 45000);
test('and follows them, which is the point of a computed property', recomputed, 50000);
test('assigning to it throws: an accessor with no setter is read-only', assignRefused, 'TypeError');
test('non-enumerable keeps it out of keys, JSON and spread, while hasOwn still finds it', [hidden, spreadDropsIt], [[['items'], '{"items":[{"naira":25000},{"naira":20000},{"naira":5000}]}', true], ['items']]);
test('redefining it as enumerable puts it into both', nowVisible, [['items', 'total'], 50000]);
test('a non-writable data property also refuses assignment', dataRefused, 'TypeError');
test('but it is a stored number, so it goes stale while the accessor stays live', [staleTotal, liveTotal], [50000, 150000]);
test('a descriptor may not describe both an accessor and a value', bothAtOnce, 'TypeError');
test('and the descriptor tells the two kinds apart', kinds, ['function', false, 'undefined']);

Read-only has two implementations and they behave differently over time. A getter with no setter recomputes on every read, so it cannot go stale; a data property with writable: false is a number that was correct once. The seventh assertion is the two side by side after the items changed: 50,000 stored against 150,000 computed.

Which to choose is a question about cost, not about safety. The accessor is right for a total, a full name, a formatted amount — anything cheap and derived. The frozen value is right when the number is a record of something, like the total at the moment an invoice was issued, where recomputing later would be wrong. Reaching for a getter to cache an expensive computation is the case where neither fits, and you want a getter that memoises into a hidden field.

Enumerability is the other half of the decision, and it is the mistake worth avoiding. An enumerable computed property gets serialised, which means it comes back from the server as a plain number that no longer recomputes and now disagrees with the items. Keep derived values non-enumerable and let the consumer ask for them, or serialise deliberately through a toJSON that says what it is doing.

The eighth assertion is a small guard rail worth knowing about: a descriptor is either a data descriptor or an accessor descriptor, and mixing value or writable with get or set is rejected before anything happens. It usually means a half-finished edit, which is exactly when you want a loud error.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.