Skip to the page

Symbols, iterators, generators and Proxy · senior

Proxy and Reflect

A Proxy wraps an object and lets you intercept basic operations (get, set, has, deleteProperty, apply, construct and more) with trap functions, and Reflect provides the default behaviour for each trap, which you call to forward the operation correctly.

The notes

What you must know

  • new Proxy(target, handler). Common traps: get, set, has, deleteProperty, ownKeys, defineProperty, apply (function calls), construct (new).
  • Reflect.get(target, key, receiver) keeps getters' this correct (the receiver is the proxy). A set trap must return true; returning false throws TypeError in strict code.
  • Uses: validation, default values, negative array indexes, logging and change tracking, read-only views, reactivity (Vue 3), Immer drafts, MobX.
  • Invariants: a trap can't lie about non-configurable or non-writable properties (TypeError).
  • Map, Set and Date methods need their internal slots, so calling them through a plain proxy throws; bind the methods to the target in the get trap.
  • #private fields don't work through a proxy, because the proxy isn't the real instance.
  • Costs: slower property access, harder debugging, and proxy !== target.

The red pen

Common traps: mistake → fix

  • Mistake: A Proxy changes the target

    Fix: it is a wrapper; the target changes only if your traps forward writes.

  • Mistake: You can skip Reflect

    Fix: without the receiver, getters and inheritance behave wrongly.

  • Mistake: A set trap can return nothing

    Fix: it must return true, or strict-mode code throws.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a Proxy used for?
  2. Build a validation proxy or a default-values proxy.
  3. Why use Reflect inside traps? What is the receiver?
  4. Which libraries use Proxies? How does Vue 3 reactivity work at a high level?
  5. Why does proxying a Map fail, and how do you fix it?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview