Proxy & Reflect API
📖 Concept
Proxy creates a wrapper around an object that intercepts and redefines fundamental operations (get, set, delete, etc.). It's a powerful metaprogramming feature.
Reflect provides methods for interceptable JavaScript operations — the same methods available as Proxy traps but as regular functions.
Traps: get, set, has, deleteProperty, apply, construct, ownKeys, getPrototypeOf, etc.
🏠 Real-world analogy: A Proxy is like a smart home assistant. When you say "set temperature to 72" (set trap), the assistant can validate it's between 60-90, log the change, and notify other devices — all transparently.
💻 Code Example
1// Basic Proxy2const user = { name: "Alice", age: 25 };3const proxy = new Proxy(user, {4 get(target, prop, receiver) {5 console.log(`Getting ${prop}`);6 return Reflect.get(target, prop, receiver);7 },8 set(target, prop, value, receiver) {9 console.log(`Setting ${prop} = ${value}`);10 if (prop === "age" && (typeof value !== "number" || value < 0)) {11 throw new TypeError("Age must be a positive number");12 }13 return Reflect.set(target, prop, value, receiver);14 }15});16proxy.name; // logs "Getting name"17proxy.age = 30; // logs "Setting age = 30"18// proxy.age = -5; // ❌ TypeError1920// Validation Proxy21function createValidated(schema) {22 return new Proxy({}, {23 set(target, prop, value) {24 const validator = schema[prop];25 if (validator && !validator(value)) {26 throw new TypeError(`Invalid value for ${prop}: ${value}`);27 }28 target[prop] = value;29 return true;30 }31 });32}33const person = createValidated({34 name: (v) => typeof v === "string" && v.length > 0,35 age: (v) => Number.isInteger(v) && v >= 0 && v <= 150,36 email: (v) => /^[^@]+@[^@]+$/.test(v)37});3839// Reactive data (Vue.js-style)40function reactive(obj, onChange) {41 return new Proxy(obj, {42 set(target, prop, value) {43 const oldValue = target[prop];44 target[prop] = value;45 if (oldValue !== value) onChange(prop, value, oldValue);46 return true;47 }48 });49}50const state = reactive({ count: 0 }, (prop, newVal) => {51 console.log(`${prop} changed to ${newVal}`);52});53state.count++; // "count changed to 1"5455// Negative array indices56function negativeArray(arr) {57 return new Proxy(arr, {58 get(target, prop) {59 const index = Number(prop);60 if (Number.isInteger(index) && index < 0) {61 return target[target.length + index];62 }63 return Reflect.get(target, prop);64 }65 });66}67const arr = negativeArray([1, 2, 3, 4, 5]);68console.log(arr[-1]); // 5
🏋️ Practice Exercise
Mini Exercise:
- Create a Proxy that makes object properties read-only
- Build a change-tracking Proxy that records all mutations
- Implement a Proxy that auto-creates nested objects on access
- Create a type-checked object using Proxy traps
⚠️ Common Mistakes
Not returning
truefromsettrap in strict mode — causes a TypeErrorForgetting to use Reflect methods inside traps — they handle edge cases you might miss
Creating Proxies for performance-critical code — Proxies add overhead to every operation
Infinite loops — a
gettrap that reads from the proxy instead of the targetNot knowing that
===comparison between proxy and target returnsfalse— they are different objects
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Proxy & Reflect API. Login to unlock this feature.