Sub topic 4
Intercepting Reads and Writes with get and set
This chapter assumes you know how to create a proxy from a target and a handler, and that you know a trap is a handler method that maps to one internal method. You should also be comfortable with prototype-chain lookup, getters and setters, and strict mode. We use Reflect.get and Reflect.set to forward operations here, but treat them as "do the normal thing" for now. The next chapter explains them in full.
The get and set traps are the most common traps, because reading and writing properties are the most common things code does with objects. They are also where most proxy bugs come from.
The Trap Signatures
The get trap intercepts the [[Get]] internal method, and the set trap intercepts [[Set]].
| Trap | Signature | Must return |
|---|---|---|
| `get` | `get(target, prop, receiver)` | The value the read should produce |
| `set` | `set(target, prop, value, receiver)` | `true` if the write succeeded, `false` otherwise |
The arguments are:
targetis the object the proxy wraps.propis the property key. It is always a string or a symbol. Numeric indexes arrive as strings, soproxy[0]gives you'0'.value(only inset) is the value being assigned.receiveris the object the operation started on. Usually this is the proxy itself. When the proxy sits on another object's prototype chain, the receiver is that other object. A later chapter covers why this matters.
Here is the smallest useful get trap. It logs each read and forwards it:
const target = { greeting: 'hello' };
const handler = {
get(target, prop, receiver) {
console.log(`get ${String(prop)}`);
return Reflect.get(target, prop, receiver);
}
};
const proxy = new Proxy(target, handler);
console.log(proxy.greeting); // logs "get greeting", then "hello"Note the String(prop). If prop is a symbol, putting it directly in a template literal throws TypeError: Cannot convert a Symbol value to a string. Many engine operations read symbol keys such as Symbol.iterator and Symbol.toPrimitive, so a logging trap that skips String() will crash the first time one of them runs.
Which Operations Trigger Which Trap
A lot of ordinary syntax reads or writes properties without looking like it. The table shows what reaches get and set, and what goes to a different trap.
| Code | Traps that fire |
|---|---|
| `proxy.x`, `proxy['x']` | `get` |
| `const { x } = proxy` | `get` for `x` |
| `proxy.method()` | `get` for `method`, then the returned function is called |
| `` `${proxy}` `` | `get` for `Symbol.toPrimitive`, then `toString` (falling back to `valueOf`) |
| `for (const v of proxy)` | `get` for `Symbol.iterator` |
| `await proxy` | `get` for `then` |
| `proxy.x = 1` | `set` |
| `proxy.x += 1`, `proxy.x++` | `get`, then `set` |
| `'x' in proxy` | `has`, not `get` |
| `Object.keys(proxy)` | `ownKeys` and `getOwnPropertyDescriptor`, not `get` |
| `Object.defineProperty(proxy, 'x', d)` | `defineProperty`, not `set` |
| `delete proxy.x` | `deleteProperty` |
The last few rows are the ones people trip on. A get trap that hides a property does not stop in or Object.keys from revealing it. If you change what reads return, check whether you also need has, ownKeys, or getOwnPropertyDescriptor to stay consistent.
The sequence below shows how a compound assignment travels through a proxy that defines both traps.
Patterns Built on get
Default values for missing properties
A get trap can return something other than undefined when a property does not exist:
const withDefault = (obj, fallback) => new Proxy(obj, {
get(target, prop, receiver) {
return prop in target ? Reflect.get(target, prop, receiver) : fallback;
}
});
const counts = withDefault({}, 0);
counts.apples += 1;
counts.apples += 1;
counts.pears += 1;
console.log(counts.apples); // 2
console.log(counts.pears); // 1
console.log(counts.kiwis); // 0The handler has no set trap, so writes go straight to the target. Any trap you leave out falls back to the default behavior.
Using prop in target rather than target[prop] !== undefined matters. A property that exists with the value undefined is still a real property, and in also finds inherited members such as toString.
Computed keys: negative array indexes
Because prop is a string, you can parse it and rewrite it before forwarding:
function negativeIndexes(array) {
return new Proxy(array, {
get(target, prop, receiver) {
if (typeof prop === 'string' && /^-\d+$/.test(prop)) {
prop = String(target.length + Number(prop));
}
return Reflect.get(target, prop, receiver);
}
});
}
const letters = negativeIndexes(['a', 'b', 'c']);
console.log(letters[-1]); // 'c'
console.log(letters[-3]); // 'a'
console.log(letters[0]); // 'a'
console.log(letters.length); // 3The typeof prop === 'string' check comes first because symbol keys such as Symbol.iterator also pass through this trap, and calling .test() on a symbol throws.
Patterns Built on set
Validation
A set trap sees the value before it is stored, so it can reject bad data:
const person = new Proxy({}, {
set(target, prop, value, receiver) {
if (prop === 'age' && (!Number.isInteger(value) || value < 0)) {
throw new TypeError('age must be a non-negative integer');
}
return Reflect.set(target, prop, value, receiver);
}
});
person.age = 30; // stored
person.age = -1; // throws TypeErrorThe trap returns the result of Reflect.set, which is true on success and false if the target refused the write (for example, because the property is non-writable). Passing that boolean through means the proxy reports failure exactly when the target would.
Change tracking
A set trap can also observe writes without blocking them:
function tracked(obj, onChange) {
return new Proxy(obj, {
set(target, prop, value, receiver) {
const old = target[prop];
const ok = Reflect.set(target, prop, value, receiver);
if (ok && old !== value) onChange(prop, old, value);
return ok;
}
});
}
const state = tracked({ count: 0 }, (prop, from, to) => {
console.log(`${String(prop)}: ${from} -> ${to}`);
});
state.count = 1; // logs "count: 0 -> 1"
state.count = 1; // logs nothing, value unchangedThe callback runs only after a successful write, so listeners never hear about a change that did not happen.
What the set Return Value Means
The boolean that set returns is the trap's success signal. What happens on false depends on whether the assignment ran in strict mode:
- In strict mode code, a falsy return makes the assignment throw a
TypeError. - In sloppy mode code, a falsy return is silently ignored. The assignment expression still evaluates to the assigned value, and nothing is stored.
ES modules and class bodies are always strict, so in modern code a set trap returning false normally means an exception.
'use strict';
const readOnly = new Proxy({ x: 1 }, {
set() {
return false;
}
});
try {
readOnly.x = 2;
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(readOnly.x); // 1Whether you throw your own error or return false is a design choice. Throwing lets you write a clear message, and it fails in sloppy mode too. Returning false matches how a non-writable property behaves, and it lets calls such as Reflect.set(proxy, ...) report failure as a boolean instead of throwing.
Common Errors
Infinite recursion through the receiver
Inside a get trap, receiver is usually the proxy. Reading from it calls the trap again:
const bad = new Proxy({ a: 1 }, {
get(target, prop, receiver) {
return receiver[prop]; // re-enters this trap forever
}
});
try {
bad.a;
} catch (err) {
console.log(err instanceof RangeError); // true: maximum call stack size exceeded
}The same happens with this[prop] in a set trap if this points at the proxy, or with receiver[prop] = value. Read and write through target or through Reflect, never through the proxy itself.
Assuming the receiver is the proxy
When a proxy sits on the prototype chain, get fires for property misses on the child object, and receiver is the child:
const proto = new Proxy({}, {
get(target, prop, receiver) {
return `missing: ${String(prop)}`;
}
});
const child = Object.create(proto);
child.own = 'here';
console.log(child.own); // 'here' (own property, trap not reached)
console.log(child.other); // 'missing: other'The same applies to set. Assigning child.newProp = 1 calls the proxy's set trap with receiver === child, and the default behavior then creates the property on child, not on the target. Code that compares receiver === proxy will be wrong in this situation.
Surprising reads from the engine and tools
A trap that changes every read can break code you did not write:
await proxyandPromise.resolve(proxy)readthen. A default-value proxy that returns a function for missing keys makes the object look like a promise, and the await never settles in the way you expect.- Template literals and string concatenation read
Symbol.toPrimitive,toString, andvalueOf. - Debuggers and
console.login some environments inspect the proxy and may or may not run its traps, so logging output can differ between Node and browsers.
When your trap returns synthetic values, guard the keys you mean to handle and forward everything else, especially symbols and then.
Traps that store data on the target directly
Writing target[prop] = value inside set instead of using Reflect.set(target, prop, value, receiver) mostly works for plain objects. It drops the receiver, though. That breaks inherited setters and the prototype-chain case above. It also hides failures: in sloppy mode, an assignment to a non-writable property returns nothing useful, so the trap would report success. The next two chapters explain why forwarding with Reflect and the receiver is the safe default.
Exercise
Given const p = new Proxy({}, { get: (t, k) => k in t ? t[k] : 'none', set: (t, k, v) => { t[k] = v * 2; } }); in strict mode, what happens when you run p.x = 5, and what does p.x return afterward?
Show answer
The set trap stores 10 on the target and then returns undefined. That is falsy, so the strict-mode assignment throws a TypeError ("trap returned falsish"). The value was already written, so p.x returns 10. The fix is to end the trap with return true; or return Reflect.set(t, k, v * 2);.
Exercise
Write a proxy factory strict(obj) whose get trap throws a ReferenceError when code reads a property that does not exist on the object or its prototype chain, while symbol keys and existing properties behave normally.
Show answer
function strict(obj) { return new Proxy(obj, { get(target, prop, receiver) { if (typeof prop === 'string' && !(prop in target)) { throw new ReferenceError(No property ${prop}); } return Reflect.get(target, prop, receiver); } }); } Using in lets inherited members such as toString through, and the typeof check skips symbols like Symbol.toPrimitive. Note that await strict(obj) will throw on the read of then, so you may want to exempt 'then' as well.
Exercise
A proxy has only a get trap that returns 'hidden' for the key 'secret'. Which of these reveal the real value or existence of secret: proxy.secret, 'secret' in proxy, Object.keys(proxy), Object.getOwnPropertyDescriptor(proxy, 'secret').value?
Show answer
proxy.secret returns 'hidden'. The other three bypass the get trap: in uses has and returns true, Object.keys uses ownKeys and getOwnPropertyDescriptor and lists 'secret', and getOwnPropertyDescriptor returns the real value. Hiding a property fully needs has, ownKeys, and getOwnPropertyDescriptor traps too.