Proxy and Reflect
Meta-programming means writing code that changes how other code behaves. A Proxy wraps an object (the target) and lets you intercept the basic operations performed on it: reading a property, writing one, checking with in, deleting, calling a function. Each intercepted operation is handled by a trap function in a handler object. Reflect is a companion object whose methods perform those same basic operations normally, so a trap can add behavior and then forward the operation. Frameworks such as Vue use proxies to know when your data changes; in application code, they power validation, logging and safe defaults.
In One Minute
new Proxy(target, handler)returns a proxy; operations on it run the handler's traps if defined, otherwise they pass through to the target.- Common traps:
get,set,has,deleteProperty,ownKeys,apply(for functions),construct(fornew). Reflect.get,Reflect.setand the otherReflectmethods perform the default behavior; use them inside traps to forward.- Uses: validation, logging, default values, read-only views, change detection (reactivity), access control.
- Proxies have a cost: every intercepted operation runs your function. Don't wrap hot data structures needlessly.
Creating a Proxy
Syntax
const proxy = new Proxy(target, {
get(target, property, receiver) { ... },
set(target, property, value, receiver) { ...; return true; },
});Example
const student = { name: "Navika", balance: 120 };
const logged = new Proxy(student, {
get(target, property, receiver) {
console.log(`read ${String(property)}`);
return Reflect.get(target, property, receiver);
},
});
console.log(logged.name);
console.log(logged.balance + 30);
console.log(student === logged, logged.missing);read name
Navika
read balance
150
read missing
false undefinedExplanation: every property read on the proxy calls the get trap with the target and the property name. The trap logs the access, then Reflect.get performs the normal lookup. The proxy is a different object from the target; operations without a trap (writes, here) go straight through to the target.
Traps and Reflect
Each trap corresponds to an internal operation, and Reflect has a method with the same name and arguments:
| Trap | Intercepts | Reflect equivalent |
|---|---|---|
get | proxy.prop, proxy[key] | Reflect.get(target, key, receiver) |
set | proxy.prop = value | Reflect.set(target, key, value, receiver) |
has | key in proxy | Reflect.has(target, key) |
deleteProperty | delete proxy.prop | Reflect.deleteProperty(target, key) |
ownKeys | Object.keys, for...in, Reflect.ownKeys | Reflect.ownKeys(target) |
getOwnPropertyDescriptor | Object.getOwnPropertyDescriptor | same name |
defineProperty | Object.defineProperty | same name |
getPrototypeOf / setPrototypeOf | Prototype access | same names |
apply | Calling a function proxy: proxy(...args) | Reflect.apply(fn, thisArg, args) |
construct | new proxy(...args) | Reflect.construct(Target, args) |
Reflect methods return results instead of throwing in many cases: Reflect.set returns true or false, and Reflect.defineProperty returns a boolean rather than throwing. That makes them ideal for forwarding inside traps.
Validation with set
The set trap sees every assignment before it happens, so it can reject bad values. It must return true for success; returning false makes the assignment fail (a TypeError in strict mode):
"use strict";
function validatedPayment(initial) {
return new Proxy(initial, {
set(target, property, value, receiver) {
if (property === "amount" && !(Number.isFinite(value) && value > 0)) {
throw new RangeError(`amount must be a positive number, got ${value}`);
}
if (!Object.hasOwn(target, property)) {
throw new TypeError(`unknown field "${String(property)}"`);
}
return Reflect.set(target, property, value, receiver);
},
});
}
const payment = validatedPayment({ name: "Advitha", amount: 45 });
payment.amount = 60;
console.log(payment.amount);
for (const [key, value] of [["amount", -5], ["amonut", 70]]) {
try {
payment[key] = value;
} catch (err) {
console.log(err.name, "-", err.message);
}
}60
RangeError - amount must be a positive number, got -5
TypeError - unknown field "amonut"The second rejection catches a typo in a field name, a bug a plain object would silently accept by creating a new property.
Defaults and Safe Access with get
const settings = new Proxy({ currency: "USD" }, {
get(target, property, receiver) {
return Reflect.has(target, property) ? Reflect.get(target, property, receiver) : `(no ${String(property)} set)`;
},
});
console.log(settings.currency, "|", settings.theme);
const strict = new Proxy({ grade: 9 }, {
get(target, property, receiver) {
if (typeof property === "string" && !(property in target)) throw new ReferenceError(`no property "${property}"`);
return Reflect.get(target, property, receiver);
},
});
console.log(strict.grade);
try {
console.log(strict.grdae);
} catch (err) {
console.log(err.message);
}USD | (no theme set)
9
no property "grdae"The second proxy turns reading a misspelled property into an error instead of a silent undefined, which can make configuration objects much easier to debug.
Read-Only Views
A proxy can give other code a view of your data that can be read but not changed, while you keep the original:
"use strict";
function readOnly(target) {
const deny = () => { throw new TypeError("This object is read-only"); };
return new Proxy(target, {
set: deny,
deleteProperty: deny,
defineProperty: deny,
get(t, p, r) {
const value = Reflect.get(t, p, r);
return value !== null && typeof value === "object" ? readOnly(value) : value;
},
});
}
const data = { fees: { tuition: 400 }, grades: [9, 10] };
const view = readOnly(data);
try { view.fees.tuition = 0; } catch (err) { console.log(err.message); }
try { view.grades.push(11); } catch (err) { console.log(err.message); }
data.fees.tuition = 415;
console.log(view.fees.tuition);This object is read-only
This object is read-only
415Unlike Object.freeze, the owner can still change the original, and the view stays up to date. The get trap wraps nested objects too, so the protection is deep.
Intercepting Function Calls with apply
A proxy around a function can intercept calls with the apply trap, for logging, timing, caching or argument checks:
function lateFee(daysLate, rate) {
return Math.min(Math.max(daysLate - 10, 0) * rate, 30);
}
const calls = [];
const traced = new Proxy(lateFee, {
apply(target, thisArg, args) {
const result = Reflect.apply(target, thisArg, args);
calls.push(`${target.name}(${args.join(", ")}) = ${result}`);
return result;
},
});
traced(14, 2);
traced(40, 2);
console.log(calls);
console.log(traced.name, traced.length);['lateFee(14, 2) = 8', 'lateFee(40, 2) = 30']
lateFee 2Properties of the function, such as name and length, pass through untouched because there's no get trap.
Reactivity: How Frameworks Use Proxies
Vue (since version 3) and libraries such as MobX wrap your state in proxies. The get trap records which properties a component reads; the set trap knows exactly which property changed, so only the affected parts of the page update. A tiny version:
function reactive(target, onChange) {
return new Proxy(target, {
set(t, property, value, receiver) {
const old = t[property];
const ok = Reflect.set(t, property, value, receiver);
if (ok && old !== value) onChange(property, old, value);
return ok;
},
});
}
const state = reactive({ balance: 450, paid: false }, (key, from, to) => {
console.log(`re-render: ${key} changed from ${from} to ${to}`);
});
state.balance = 250;
state.balance = 250;
state.paid = true;re-render: balance changed from 450 to 250
re-render: paid changed from false to trueThe second assignment didn't trigger anything because the value didn't change. Real frameworks add dependency tracking, batching and nested objects, but the core mechanism is this set trap.
Limitations and Costs
| Limitation | Detail |
|---|---|
| Identity | A proxy is not === its target; code holding both may be confused |
| Private fields and internal slots | Built-ins like Map, Set and Date, and classes with #private fields, use internal slots the proxy can't forward: new Proxy(new Map(), {}).get("a") throws TypeError unless methods are bound to the target |
| Performance | Every trapped operation calls a function; avoid proxies on objects accessed in tight loops |
| Invariants | Traps must respect the target's rules (for example, can't report a non-configurable property as missing); violations throw TypeError |
| Debugging | Behavior is hidden behind traps, which can surprise readers |
Proxy.revocable(target, handler) returns { proxy, revoke }; after revoke(), every operation on the proxy throws, which is useful for handing out access you may need to withdraw.
In Practice
The Fee Tracker wraps settings loaded from a file in a validating, change-logging proxy, so a bad value or a mistyped key fails immediately, and every change is recorded for an audit trail:
"use strict";
const SCHEMA = {
currency: (v) => typeof v === "string" && /^[A-Z]{3}$/.test(v),
pageSize: (v) => Number.isInteger(v) && v >= 10 && v <= 100,
lateFeeCap: (v) => Number.isFinite(v) && v >= 0,
};
function guardedSettings(initial, audit) {
return new Proxy({ ...initial }, {
set(target, key, value, receiver) {
const check = SCHEMA[key];
if (!check) throw new TypeError(`Unknown setting "${String(key)}"`);
if (!check(value)) throw new RangeError(`Invalid value for ${String(key)}: ${JSON.stringify(value)}`);
audit.push(`${String(key)}: ${JSON.stringify(target[key])} -> ${JSON.stringify(value)}`);
return Reflect.set(target, key, value, receiver);
},
});
}
const audit = [];
const settings = guardedSettings({ currency: "USD", pageSize: 25, lateFeeCap: 30 }, audit);
settings.pageSize = 50;
for (const [k, v] of [["pageSize", 500], ["pagesize", 20], ["currency", "usd"]]) {
try { settings[k] = v; } catch (err) { console.log(err.message); }
}
console.log(audit);Invalid value for pageSize: 500
Unknown setting "pagesize"
Invalid value for currency: "usd"
['pageSize: 25 -> 50']Common Mistakes
Forgetting to return true from set. In strict mode, the assignment then throws. Return Reflect.set(...).
Forwarding without receiver. Getters and setters on the target may see the wrong this. Pass all trap arguments to Reflect.
Proxying Map, Set, Date or classes with private fields naively. Their methods need the real object. Bind methods to the target in the get trap, or wrap at a higher level.
Using proxies for a handful of known properties. Getters, setters and classes are clearer.
Under the Hood
Every object operation in the specification is defined in terms of internal methods: [[Get]], [[Set]], [[HasProperty]], [[Delete]], [[OwnPropertyKeys]], [[Call]], [[Construct]] and a few more. Ordinary objects implement them with the standard algorithms (walking the prototype chain for [[Get]], and so on). A proxy is an exotic object whose internal methods look up the corresponding trap on the handler and call it if present, otherwise forwarding to the target. After a trap runs, the engine checks invariants against the target (for example, get must return the actual value for a non-writable, non-configurable property), which keeps proxies from lying about frozen objects. Reflect's methods are the ordinary internal methods exposed as functions, which is why they line up one-to-one with traps. Engines can't optimize proxy access with inline caches the way they do for normal objects, since any trap might do anything; that's the source of the performance cost.
Interview Corner
What is a Proxy in JavaScript?
An object that wraps a target and intercepts fundamental operations (property get and set, in, delete, key enumeration, function calls, new) through trap functions defined in a handler. Untrapped operations pass through to the target. Used for validation, logging, defaults, access control and reactive state.
Why use Reflect inside proxy traps?
Reflect methods perform the default behavior of each internal operation with the same signatures as the traps, return booleans instead of throwing where appropriate, and accept a receiver so getters and setters run with the correct this. They make forwarding correct and concise.
Practice
Challenge: Create withNegativeIndexes(array) that returns a proxy where proxy[-1] reads the last item, proxy[-2] the second to last, and so on, while normal indexes still work.
Show solution
function withNegativeIndexes(array) {
return new Proxy(array, {
get(target, property, receiver) {
if (typeof property === "string" && /^-\d+$/.test(property)) {
property = String(target.length + Number(property));
}
return Reflect.get(target, property, receiver);
},
});
}
const fees = withNegativeIndexes([120, 85, 45]);
console.log(fees[0], fees[-1], fees[-2], fees.length);120 45 85 3(Arrays now have at(-1) for this, but the exercise shows how property keys reach a trap as strings.)
Key Takeaways
| Trap | Triggered by |
|---|---|
get | proxy.x |
set | proxy.x = v (return true) |
has | "x" in proxy |
deleteProperty | delete proxy.x |
ownKeys | Object.keys(proxy) |
apply | proxy(...) for functions |
Was this tutorial helpful?