Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Default values with Proxy and Reflect in JavaScript

110 Reflect, a defaulting getter, and the receiver that matters

fair

Write withDefaults(target, fallback): a Proxy whose get trap returns a default for any key the target does not own, where the fallback may be a value or a function of the key. Then prove why Reflect.get needs its third argument by putting a getter on the target that reads a key which only exists as a default.

Stuck? Three hints, smallest first
  1. 1. Object.hasOwn(target, key) decides whether to read or to invent. Reflect.get(target, key) does the reading.
  2. 2. Reflect.get(target, key, receiver) takes a third argument that becomes this inside any getter it runs. Leave it out and this is the bare target.
  3. 3. The get trap changes reads and nothing else, so in, Object.keys and JSON.stringify still report the truth. That inconsistency is the thing to be careful about.

The answer

const withDefaults = (target, fallback) =>
  new Proxy(target, {
    get(obj, key, receiver) {
      if (Object.hasOwn(obj, key)) return Reflect.get(obj, key, receiver);
      return typeof fallback === 'function' ? fallback(key) : fallback;
    },
  });

const salesByDay = { mon: 12000, tue: 9000 };
const sales = withDefaults(salesByDay, 0);
const named = withDefaults(salesByDay, (key) => `no sales for ${String(key)}`);

const present = sales.mon;
const missing = sales.sun;
const explained = named.sun;
const inDisagrees = ['sun' in sales, sales.sun];
const stillHonest = [Object.keys(sales), JSON.stringify(sales), { ...sales }];

const basket = {
  units: 3,
  price: 4500,
  get subtotal() { return this.units * this.price; },
  get total() { return this.subtotal + this.deliveryFee; },   // deliveryFee is not here
};
const tally = withDefaults(basket, 0);
const noReceiver = new Proxy(basket, {
  get(obj, key) {
    return Object.hasOwn(obj, key) ? Reflect.get(obj, key) : 0;   // receiver dropped
  },
});

const throughProxy = [tally.subtotal, tally.total];
const straightAtTheObject = Number.isNaN(basket.total);
const withoutReceiver = Number.isNaN(noReceiver.total);

const reflectBasics = [Reflect.get(salesByDay, 'mon'), Reflect.has(salesByDay, 'sun'), Reflect.ownKeys({ a: 1, b: 2 })];

console.log('defaults :', present, missing, '| named:', explained);
console.log('in says  :', inDisagrees, '| keys:', stillHonest[0]);
console.log('receiver :', throughProxy);
console.log('without  :', withoutReceiver, '| direct:', straightAtTheObject);

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('a key the target owns reads normally', present, 12000);
test('a key it does not own comes back as the default', missing, 0);
test('a function fallback is handed the key, so the default can mention it', explained, 'no sales for sun');
test('in still tells the truth, so reads and membership now disagree', inDisagrees, [false, 0]);
test('keys, JSON and the spread all see only the real entries', stillHonest, [['mon', 'tue'], '{"mon":12000,"tue":9000}', { mon: 12000, tue: 9000 }]);
test('passing the receiver makes this inside a getter the proxy, so it sees defaults', throughProxy, [13500, 13500]);
test('the same getter read straight off the object adds undefined and gets NaN', straightAtTheObject, true);
test('and dropping the third argument to Reflect.get puts it back to NaN', withoutReceiver, true);
test('Reflect is the function form of the operators: get, has, ownKeys', reflectBasics, [12000, false, ['a', 'b']]);

The receiver is the subtle part, and the two NaN assertions are the reason to care. basket.total reads this.deliveryFee, which does not exist, so the arithmetic gives NaN. Read the same getter through the proxy with the receiver forwarded and this is the proxy, so this.deliveryFee goes back through the trap and picks up the default — the getter suddenly works. Drop the third argument and this is the plain target again and it breaks. Forwarding the receiver is not optional politeness; it is what makes a proxy compose with getters, and the same argument applies to Reflect.set.

The honesty assertions are the warning. A get trap changes reads only, so 'sun' in sales is false while sales.sun is 0, and Object.keys, the spread and JSON.stringify all report the target unchanged. Code that checks for a key before reading it therefore takes a different path from code that just reads, which is a genuinely confusing bug to be handed. Trap has and ownKeys as well if the illusion needs to be complete — and think hard about whether it should be.

One more thing the trap sees: every key anybody asks for, including then, toJSON and Symbol.toPrimitive. A default that answers then with a function makes your object look like a promise, and await on it will do something you did not plan. A defaulting proxy should either exclude symbol keys and the well-known names, or be kept well away from anything that awaits.

Newsletter

New writing, when it lands.

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