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

codeTap to expand ⛶
1// Basic Proxy
2const 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; // ❌ TypeError
19
20// Validation Proxy
21function 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});
38
39// 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"
54
55// Negative array indices
56function 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:

  1. Create a Proxy that makes object properties read-only
  2. Build a change-tracking Proxy that records all mutations
  3. Implement a Proxy that auto-creates nested objects on access
  4. Create a type-checked object using Proxy traps

⚠️ Common Mistakes

  • Not returning true from set trap in strict mode — causes a TypeError

  • Forgetting 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 get trap that reads from the proxy instead of the target

  • Not knowing that === comparison between proxy and target returns false — they are different objects

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Proxy & Reflect API. Login to unlock this feature.