Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Getters and setters in object literals in JavaScript

78 Accessors in an object literal, and the getter you cannot write to

fair

Give a wallet object a naira accessor over its kobo field: the getter divides, the setter validates and rounds. Add a computed accessor name and a getter-only property, then show what strict mode does when you assign to a getter with no setter, and what a spread copy turns your accessor into.

Stuck? Three hints, smallest first
  1. 1. A getter and a setter of the same name are two halves of one property, and reading it looks exactly like reading a field.
  2. 2. Assigning to a property that only has a getter is a silent no-op in sloppy mode and a TypeError in strict mode.
  3. 3. Spread reads values, so it calls the getter once and stores the result as an ordinary data property.

The answer

const unit = 'naira';

const wallet = {
  kobo: 500000,
  get [unit]() {
    return this.kobo / 100;
  },
  set [unit](value) {
    if (typeof value !== 'number' || Number.isNaN(value)) throw new TypeError('naira must be a number');
    this.kobo = Math.round(value * 100);
  },
  get label() {
    return `₦${this.naira.toFixed(2)}`;
  },
};

const readAsNumber = [wallet.naira, typeof wallet.naira];
wallet.naira = 62.505;
const afterWrite = [wallet.kobo, wallet.label];

let rejected;
try {
  wallet.naira = 'plenty';
} catch (error) {
  rejected = error.constructor.name;
}
const unchanged = wallet.kobo;

let readOnly;
try {
  wallet.label = 'free';
} catch (error) {
  readOnly = error.constructor.name;
}

const descriptor = Object.getOwnPropertyDescriptor(wallet, 'naira');
const descriptorShape = [typeof descriptor.get, typeof descriptor.set, 'value' in descriptor, descriptor.enumerable];
const keysIncludeAccessors = Object.keys(wallet);
const serialised = JSON.parse(JSON.stringify(wallet));

const copy = { ...wallet };
const copyDescriptor = Object.getOwnPropertyDescriptor(copy, 'naira');
copy.kobo = 1;
const copyWentStale = [copy.naira, typeof copyDescriptor.get, copyDescriptor.value];

console.log('read   :', readAsNumber, '| after write:', afterWrite);
console.log('reject :', rejected, unchanged, '| read-only:', readOnly);
console.log('shape  :', descriptorShape, keysIncludeAccessors);
console.log('copy   :', copy, copyWentStale);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a getter reads like a field, not like a method', readAsNumber, [5000, 'number']);
test('the setter is where the conversion and the rounding live', afterWrite, [6251, '₦62.51']);
test('so validation in a setter guards every future write', [rejected, unchanged], ['TypeError', 6251]);
test('and in strict mode assigning to a getter-only property throws', readOnly, 'TypeError');
test('the descriptor holds get and set, and no value at all', descriptorShape, ['function', 'function', false, true]);
test('accessors are enumerable own properties, so keys lists them', keysIncludeAccessors, ['kobo', 'naira', 'label']);
test('and JSON.stringify serialises what the getter returns', serialised, { kobo: 6251, naira: 62.51, label: '₦62.51' });
test('a spread copy freezes the accessor into a plain value', copyWentStale, [62.51, 'undefined', 62.51]);

An accessor lets a computed value be read like a stored one, which is exactly right for a derived quantity: kobo is the truth, naira is a view of it, and no caller has to remember to divide. The setter is the other half of the deal and the more valuable one, because it is the single place a value can be validated, rounded or normalised before it is stored.

Two strict-mode facts. Assigning to a property with only a getter throws a TypeError here; in sloppy mode the same line does nothing and reports nothing, which is one of the quieter bugs in old code. And the descriptor makes the distinction plain: an accessor has get and set, a data property has value and writable, and no property has both.

The spread result is the one to remember. { ...wallet } invokes the getter and stores the number it returned, so the copy has a frozen snapshot with no live link to kobo: change copy.kobo and copy.naira keeps its old answer. If you need to carry an accessor across, Object.defineProperties with Object.getOwnPropertyDescriptors is the copy that preserves it.

Newsletter

New writing, when it lands.

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