🟑 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