MediumModern JS📖 Theory Question

What is Proxy and how does it enable metaprogramming?

💡

Hint

Intercept fundamental object operations (get, set, has, deleteProperty) with handler traps

Full Answer

A Proxy wraps an object and intercepts fundamental operations using "trap" handler methods.

const handler = {
  get(target, prop, receiver) {
    console.log(`Getting: ${prop}`);
    return Reflect.get(target, prop, receiver); // ← always use Reflect
  },
  set(target, prop, value, receiver) {
    if (typeof value !== 'number') throw new TypeError('Numbers only');
    return Reflect.set(target, prop, value, receiver);
  },
  has(target, prop) {
    return prop in target; // intercepts 'in' operator
  },
  deleteProperty(target, prop) {
    if (prop.startsWith('_')) throw new Error('Cannot delete private');
    return Reflect.deleteProperty(target, prop);
  }
};

const obj = new Proxy({}, handler);
obj.x = 42;
obj.x;         // logs "Getting: x" → 42
'x' in obj;    // calls has trap
obj.y = 'str'; // TypeError

// Real-world use cases:
// 1. Validation
// 2. Reactive state (Vue 3 uses Proxy for reactivity!)
// 3. Default property values
// 4. Logging / debugging
// 5. Negative array indexing
const arr = new Proxy([], {
  get: (t, p) => t[p < 0 ? t.length + +p : p]
});
arr[-1]; // last element
💡 Always use Reflect inside Proxy traps — it handles edge cases with prototype chains and getters/setters correctly. Reflect methods mirror Proxy trap signatures exactly.

More Modern JS Questions

MediumWhat are generators and when would you use them?→EasyWhat is optional chaining (?.) and nullish coalescing (??)?→EasyWhat are tagged template literals and what are they used for?→EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint