Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Object with a default value for missing keys in JavaScript

57 An object with a default value

fair

Build withDefault(fallback, seed): a proxy where a missing key reads as fallback instead of undefined, so a tally needs no ?? 0. Then check whether in, Object.keys and JSON.stringify agree with the trap.

Stuck? Three hints, smallest first
  1. 1. Reflect.has(target, key) tells you whether the key is really there before you invent a value.
  2. 2. The get trap does not create anything, so nothing else about the object changed.
  3. 3. Trapping has as well makes in answer true — for every key, including nonsense.

The answer

const withDefault = (fallback, seed = {}) => new Proxy({ ...seed }, {
  get(target, key, receiver) {
    return Reflect.has(target, key) ? Reflect.get(target, key, receiver) : fallback;
  },
});

const fares = withDefault(0, { Yaba: 300, Ikeja: 500 });

const seeded = fares.Yaba;
const missing = fares.Lekki;
const tallied = fares.Lekki + fares.Ikeja + 100;      // no ?? 0 anywhere
const inSaysNo = 'Lekki' in fares;
const realKeys = Object.keys(fares);

fares.Lekki = 700;                                     // set is untrapped, so this is real
const nowPresent = ['Lekki' in fares, fares.Lekki];
const serialised = JSON.parse(JSON.stringify(fares));

// The same idea with `has` trapped too, which is a much bigger claim.
const everything = new Proxy({ Yaba: 300, Ikeja: 500 }, {
  get: (t, k, r) => (Reflect.has(t, k) ? Reflect.get(t, k, r) : 0),
  has: () => true,
});
const inSaysYes = ['Ojota' in everything, 'nonsense' in everything];
const keysUnmoved = Object.keys(everything);

console.log('seeded, missing:', seeded, missing);
console.log('tallied        :', tallied);
console.log('real keys      :', realKeys);
console.log('serialised     :', serialised);

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 missing key reads as the fallback', [seeded, missing], [300, 0]);
test('so arithmetic over unknown stops needs no guard', tallied, 600);
test('but `in` still says the key is absent: get invents, it does not create', inSaysNo, false);
test('and Object.keys lists only what is really there', realKeys, ['Yaba', 'Ikeja']);
test('assigning through it creates a real key, and then `in` agrees', nowPresent, [true, 700]);
test('serialising shows the real keys only, never the default', serialised, { Yaba: 300, Ikeja: 500, Lekki: 700 });
test('a has trap makes `in` answer true for anything at all', inSaysYes, [true, true]);
test('yet ownKeys is untrapped, so Object.keys is unchanged by that lie', keysUnmoved, ['Yaba', 'Ikeja']);

{ ...seed } rather than seed is deliberate: a proxy wraps a target it does not own, and handing it the caller's object means writes through the proxy mutate their object. Copying makes the wrapper self-contained.

The interesting part is where the illusion stops. A get trap answers reads and nothing else, so the object still has two keys: in says no, Object.keys says no, JSON.stringify says no. That is usually what you want — a tally that reads as 0 for every Lagos stop but serialises only the ones with fares.

Trapping has too is where it gets dangerous. 'nonsense' in everything now answers true, and any code doing feature detection — if ('toJSON' in obj), if ('then' in obj) — is now being lied to. The last assertion shows how inconsistent that leaves the object: in claims every key exists while Object.keys lists two, because those go through different traps. Traps are independent, and a proxy is only as coherent as you make it.

One quiet hazard with any get trap: JSON.stringify asks for toJSON first. A fallback of 0 is not callable so it is ignored, but a fallback that happened to be a function would be called as toJSON and would decide the whole serialisation.

Newsletter

New writing, when it lands.

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