JavaScriptHard
What is Proxy?
A Proxy wraps a target object and lets you intercept fundamental operations on it (reading, writing, deleting, checking, enumerating, calling) through handler functions called traps.
Syntax
const proxy = new Proxy(target, handler). Any trap you do not define falls through to the target.
Common traps
get(target, prop, receiver): property reads.set(target, prop, value, receiver): writes; returntrueon success (returningfalsethrows in strict mode).has(theinoperator),deleteProperty,ownKeys(Object.keys,for...in),getOwnPropertyDescriptor,defineProperty.applyandconstructwhen the target is a function.
Real-world uses
- Reactivity: Vue 3 and MobX track which properties a component reads and re-render when they change.
- Validation of writes (see "How to use Proxy for validation").
- Default values for missing properties, and negative array indexes.
- Logging, tracing and access control (read-only views, hiding private keys).
- API clients that build URLs from property access (
api.users.get()). - Mocks and test spies.
Best practices
- Inside traps, use
Reflectmethods (Reflect.get(target, prop, receiver)) to perform the default behaviour correctly, including getters and inheritance. - Respect invariants: for example, a non-configurable property must keep reporting its real value, or the engine throws.
Costs and limits
Every intercepted operation runs your code, so proxies are slower than plain objects. Avoid them in very hot paths. Some built-ins with internal slots (Map, Date, private class fields) do not work transparently through a proxy without extra care.
Code example
js
1// Default values + read logging2const settings = new Proxy(3 { theme: "dark" },4 {5 get(target, prop, receiver) {6 if (!(prop in target)) return `<default ${String(prop)}>`;7 return Reflect.get(target, prop, receiver);8 },9 }10);11console.log(settings.theme, settings.language); // dark <default language>1213// Negative indexes for arrays14const withNegativeIndex = (arr) =>15 new Proxy(arr, {16 get(target, prop, receiver) {17 const i = Number(prop);18 if (Number.isInteger(i) && i < 0) prop = String(target.length + i);19 return Reflect.get(target, prop, receiver);20 },21 });22const letters = withNegativeIndex(["a", "b", "c"]);23console.log(letters[-1], letters[0], letters.length); // c a 32425// A tiny reactive store: run a callback whenever a property changes26function reactive(obj, onChange) {27 return new Proxy(obj, {28 set(target, prop, value, receiver) {29 const old = target[prop];30 const ok = Reflect.set(target, prop, value, receiver);31 if (ok && old !== value) onChange(prop, old, value);32 return ok;33 },34 });35}36const state = reactive({ count: 0 }, (prop, from, to) => console.log(`${prop}: ${from} -> ${to}`));37state.count++; // count: 0 -> 138state.count = 1; // no change, no log39state.count = 5; // count: 1 -> 5
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.