Proxy and Reflect API

Difficulty: Advanced

Question

What are the Proxy and Reflect APIs in JavaScript, and how do they let you intercept and customise fundamental object operations (meta-programming)?

Answer

A Proxy wraps a target object and lets you intercept fundamental operations on it, such as reading a property, assigning one, deleting one, checking in, or calling a function, through handler methods called traps. Reflect is a built-in namespace object whose static methods (Reflect.get, Reflect.set, Reflect.has and so on) perform the default version of each of those operations, so a trap can add behaviour and then forward to the normal semantics. Together they give JavaScript real meta-programming: code that changes how objects behave rather than what data they hold.

How a Proxy intercepts an operation

new Proxy(target, handler) returns a new object. Every operation on the proxy is routed to the matching trap on handler; if the trap is missing, the operation falls through to the target unchanged. There are 13 traps, one for each internal method in the spec:

A trap receives the target, the property key and, for get and set, a receiver argument, which is the object the operation was originally performed on (usually the proxy itself, or an object that inherits from it).

Why Reflect exists and why you should use it inside traps

Before ES2015, the default behaviours were scattered: delete obj[k], k in obj, Object.defineProperty, Function.prototype.apply. Reflect gathers them into one place, with one method per trap and identical signatures. That makes forwarding trivial: return Reflect.set(target, key, value, receiver).

Passing receiver matters. If the target has a getter that uses this, target[key] runs the getter with this set to the raw target, bypassing the proxy. Reflect.get(target, key, receiver) runs it with this set to the proxy, so nested accesses are still intercepted. Reflect methods also return booleans (Reflect.set, Reflect.defineProperty) instead of throwing, which is exactly what set and defineProperty traps must return.

Real-world uses

Proxy vs Object.defineProperty

AspectProxyObject.defineProperty
ScopeWhole object, including keys added laterOne existing property at a time
Detects new / deleted keysYes (set, deleteProperty)No
Array index and length changesYesNot reliably
IdentityProxy is a different object from targetSame object
PolyfillableNoYes (ES5)

This table is why Vue 2 needed Vue.set for new keys and Vue 3 does not.

Gotchas interviewers probe

An operation travelling through a Proxy. Try different operations, turn the Proxy off, or freeze the target under Tweak.
  1. Traps intercept operations: get, set and deleteProperty run before the target is touched.
  2. Validation: The set trap throws a RangeError for a negative age.
  3. Defaults: The get trap can return a fallback for missing keys.
  4. Reflect forwards: Reflect.get / set / deleteProperty perform the default behaviour.

Code examples

Validation proxy with Reflect forwarding

const orderValidator = {
  set(target, key, value, receiver) {
    if (key === 'amountInPaise') {
      if (!Number.isInteger(value)) throw new TypeError('amountInPaise must be an integer');
      if (value <= 0) throw new RangeError('amountInPaise must be positive');
    }
    // Forward to default behaviour; returns true on success
    return Reflect.set(target, key, value, receiver);
  },
  deleteProperty(target, key) {
    if (key === 'id') throw new Error('id cannot be deleted');
    return Reflect.deleteProperty(target, key);
  },
};

const order = new Proxy({ id: 'ord_1' }, orderValidator);
order.amountInPaise = 49900;
console.log(order.amountInPaise);

try {
  order.amountInPaise = -5;
} catch (e) {
  console.log(e.name + ': ' + e.message);
}

The set trap validates before writing, and Reflect.set does the real assignment while preserving the receiver. Returning its boolean result keeps strict-mode semantics correct.

Tiny reactive system (the idea behind Vue 3)

let activeEffect = null;
const deps = new Map(); // key -> Set of effects

function reactive(obj) {
  return new Proxy(obj, {
    get(target, key, receiver) {
      if (activeEffect) {
        if (!deps.has(key)) deps.set(key, new Set());
        deps.get(key).add(activeEffect); // track
      }
      return Reflect.get(target, key, receiver);
    },
    set(target, key, value, receiver) {
      const ok = Reflect.set(target, key, value, receiver);
      deps.get(key)?.forEach(fn => fn()); // trigger
      return ok;
    },
  });
}

function effect(fn) {
  activeEffect = fn;
  fn();
  activeEffect = null;
}

const cart = reactive({ items: 2 });
effect(() => console.log('Cart badge:', cart.items));
cart.items = 3;

Reading a property inside an effect records a dependency, and writing to it re-runs every dependent effect. Real libraries add per-object dependency maps, batching and deep wrapping, but the core mechanism is these two traps.

The Map internal-slot gotcha

const map = new Map([['a', 1]]);

const broken = new Proxy(map, {});
try {
  broken.get('a');
} catch (e) {
  console.log(e.constructor.name);
}

const fixed = new Proxy(map, {
  get(target, key, receiver) {
    const value = Reflect.get(target, key, receiver);
    // Bind methods so `this` is the real Map, not the proxy
    return typeof value === 'function' ? value.bind(target) : value;
  },
});
console.log(fixed.get('a'));

Map methods read an internal slot that only exists on the real Map, so they fail when called with the proxy as this. Binding methods to the target fixes it, which is why reactive libraries special-case collections.

Key points

Common follow-up questions

Interview tips

Concepts covered

Proxy, Reflect, Handler Traps, Invariants, Meta-programming, Reactivity

More JavaScript Interview questions