Proxies and Reflect
Overview
A Proxy wraps an object and lets you step in whenever someone reads, writes or deletes its properties.
const target = { title: 'Proxies' };
const watched = new Proxy(target, {
get(obj, key) {
console.log(`Reading ${String(key)}`);
return obj[key];
},
});
watched.title; // logs "Reading title", returns 'Proxies'The second argument is a handler object. Its functions — called traps — replace the normal behaviour.
The proxy looks and behaves like the original object to everyone using it. Any operation without a trap passes straight through to the target unchanged.
Common traps
| Trap | Runs for |
|---|---|
get(target, key, receiver) |
reading proxy.key |
set(target, key, value, receiver) |
proxy.key = value |
has(target, key) |
key in proxy |
deleteProperty(target, key) |
delete proxy.key |
ownKeys(target) |
Object.keys(proxy), for…in |
apply(target, thisArg, args) |
calling a proxied function |
Keys can be strings or symbols, which is why the examples use String(key) before printing.
Validation
const profile = new Proxy({}, {
set(obj, key, value) {
if (key === 'age' && !Number.isInteger(value)) {
throw new TypeError('Age must be a whole number');
}
obj[key] = value;
return true; // tell JavaScript the assignment succeeded
},
});
profile.age = 30; // fine
profile.age = 'old'; // TypeError: Age must be a whole numberA set trap must return true. Returning false (or nothing) means “the assignment failed”, which throws a TypeError in strict mode.
Default values
A get trap can answer for properties that don’t exist:
const withDefaults = (obj, fallback) =>
new Proxy(obj, {
get: (target, key) => (key in target ? target[key] : fallback),
});
const counts = withDefaults({}, 0);
counts.apples++; // no need to check for undefined first
counts.apples; // 1
counts.pears; // 0Reflect
Reflect has a method for each trap that performs the default behaviour. Using it inside traps keeps edge cases (like getters and inheritance) working correctly:
const logged = new Proxy(target, {
set(obj, key, value, receiver) {
console.log('set', key);
return Reflect.set(obj, key, value, receiver);
},
});Reflect.set also returns true or false, so you can return its result directly from the trap. The pairs line up one to one: get ↔ Reflect.get, has ↔ Reflect.has, deleteProperty ↔ Reflect.deleteProperty, and so on.
Reflect is useful outside proxies too — Reflect.ownKeys(obj) lists every own key, including symbols.
A tiny reactive store
This is the core idea behind frameworks like Vue: change the data, and the page updates itself.
function reactive(data, onChange) {
return new Proxy(data, {
set(target, key, value, receiver) {
const ok = Reflect.set(target, key, value, receiver);
onChange(key, value);
return ok;
},
});
}
const state = reactive({ count: 0 }, () => {
counterEl.textContent = state.count;
});
button.addEventListener('click', () => {
state.count++; // the page updates automatically
});Things to know
- Proxies only intercept operations done through the proxy. Code holding the original
targetbypasses the traps entirely — so usually you keep only the proxy. - They’re shallow: a nested object read through a proxy is the plain nested object, unless your
gettrap wraps it too. - Some built-in objects, like
MapandDate, use internal slots that don’t work through a simple proxy.
Where you’ll meet them
Frameworks such as Vue use proxies to notice when your data changes and update the page automatically. Testing libraries use them to create mock objects, and some libraries use them to give friendly error messages for misspelled properties.
Use sparingly. Proxies add a little overhead and can make code surprising to read. Plain functions and classes are usually enough.
Log every change
Wrap state in a Proxy that logs key → value whenever a property is set. Then add a get trap that returns 0 for any property that doesn’t exist.
const state = { count: 0 };const state = new Proxy({ count: 0 }, {
set(target, key, value, receiver) {
console.log(`${String(key)} → ${value}`);
return Reflect.set(target, key, value, receiver);
},
get(target, key, receiver) {
return key in target ? Reflect.get(target, key, receiver) : 0;
},
});
state.count = 1; // logs "count → 1"
state.missing; // 0Summary
- A Proxy wraps an object and lets you intercept operations on it.
- Handler functions (traps) such as
get,set,hasanddeletePropertyrun instead of the default. - A
settrap must returntruefor success. Reflectperforms the default behaviour from inside a trap.- Proxies power validation, logging, defaults and reactive frameworks — use them sparingly.