Skip to content

OutputNot attempted

Proxy with a default value

const target = { a: 1 };
const proxy = new Proxy(target, {
get(obj, key) {
return key in obj ? obj[key] : 42;
},
});
console.log(proxy.a, proxy.b, target.b);
proxy.c = 3;
console.log(target.c, 'c' in proxy);

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

The get trap intercepts reads only. Missing keys fall back to 42, but the target itself is untouched (target.b is undefined). With no set or has trap, writes and in go straight through to the target.