# Proxy and Reflect API

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

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-proxy-reflect
Last updated: 2026-11-28

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:

- `get`, `set`, `has`, `deleteProperty`, `ownKeys`
- `getOwnPropertyDescriptor`, `defineProperty`
- `getPrototypeOf`, `setPrototypeOf`, `isExtensible`, `preventExtensions`
- `apply` and `construct` (only meaningful when the target is a function)

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

- **Reactivity**: Vue 3's `reactive()` uses a `get` trap to track which component read a property and a `set` trap to trigger re-renders. MobX and Immer also rely on proxies (Immer records writes to a draft and produces an immutable copy).
- **Validation**: reject `order.amountInPaise = -100` at the moment of assignment.
- **Defaults and safe access**: return a fallback for missing config keys instead of `undefined`.
- **Logging, access control, API clients**: a `get` trap can turn `api.users.list()` into an HTTP call without defining every method.
- **Negative array indexes** or read-only views of shared state.

### Proxy vs Object.defineProperty

| Aspect | Proxy | Object.defineProperty |
| --- | --- | --- |
| Scope | Whole object, including keys added later | One existing property at a time |
| Detects new / deleted keys | Yes (`set`, `deleteProperty`) | No |
| Array index and `length` changes | Yes | Not reliably |
| Identity | Proxy is a different object from target | Same object |
| Polyfillable | No | Yes (ES5) |

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

### Gotchas interviewers probe

- **Invariants**: traps cannot lie about non-configurable properties. If the target has a non-writable, non-configurable property, a `get` trap must return its real value or a `TypeError` is thrown.
- **Internal slots**: built-ins like `Map`, `Set`, `Date` and private class fields store data in internal slots. `new Proxy(new Map(), {}).get('x')` throws because `this` is the proxy, not the Map. You must bind methods to the target.
- **Identity**: `proxy === target` is `false`, so `WeakMap` lookups or `Set` membership keyed on the original object will miss.
- **Performance**: every trapped operation is a function call. Proxies on hot paths (tight loops over large arrays) are measurably slower than plain objects.
- **Revocable proxies**: `Proxy.revocable()` returns `{ proxy, revoke }`; after `revoke()`, any operation throws. Useful for handing temporary access to untrusted code.

**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

- Proxy has 13 traps, one per internal object method; missing traps forward to the target.
- Reflect mirrors every trap with the same signature, so forwarding is one line.
- Pass the receiver to Reflect.get and Reflect.set so getters and setters see the proxy as this.
- Traps must respect invariants of non-configurable, non-extensible targets or a TypeError is thrown.
- Proxies cannot be polyfilled, are not identical to their target, and break built-ins with internal slots unless methods are bound.
- Vue 3, MobX and Immer all build on Proxy.

## Common follow-up questions

- How would you make a deeply reactive object that wraps nested objects lazily?
- Why did Vue 2 need Vue.set and why does Vue 3 not need it?
- What is Proxy.revocable and when would you use it?
- What happens if a get trap returns a different value for a non-configurable, non-writable property?
- How would you implement negative array indexing with a Proxy?

## Interview tips

- Name the receiver argument and explain why Reflect.get(target, key, receiver) is safer than target\[key\]; most candidates skip this.
- Tie the answer to a real system such as Vue 3 reactivity or Immer to show you know where Proxy is used in practice.
- Mention the trade-offs (performance, identity, internal slots) instead of presenting Proxy as free magic.

## Concepts covered

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

Previous: [Symbols & Well-Known Symbols](https://www.internhack.in/learn/interview/javascript-interview/js-symbols) · Next: [WeakMap and WeakSet](https://www.internhack.in/learn/interview/javascript-interview/js-weakmap-weakset) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Generator Functions](https://www.internhack.in/learn/interview/javascript-interview/js-generators)
- [Optional Chaining and Nullish Coalescing](https://www.internhack.in/learn/interview/javascript-interview/js-optional-chaining-nullish)
- [Currying and Function Composition](https://www.internhack.in/learn/interview/javascript-interview/js-currying-composition)
- [Memoization](https://www.internhack.in/learn/interview/javascript-interview/js-memoization)
- [Property Descriptors and Object.defineProperty](https://www.internhack.in/learn/interview/javascript-interview/js-property-descriptors)
- [Deep Cloning: structuredClone vs JSON](https://www.internhack.in/learn/interview/javascript-interview/js-structuredclone)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
