Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 156 ยท Built-in Tools

Proxy and Reflect

Wrap objects in a JavaScript Proxy to intercept reads, writes and calls. Use traps with Reflect for validation, logging, defaults and reactive state.

Normally, reading user.name simply looks up a property, and user.age = 30 simply stores a value. A Proxy lets you step in between: it wraps an object and runs your code whenever someone reads a property, writes one, deletes one, checks in, calls a function and more. The code using the object doesn't need to know โ€” it looks and behaves like the original.

This is the machinery behind features in popular frameworks: Vue's reactivity system, validation libraries, mocking tools in tests and "observable" state stores. In this lesson you will learn how proxies and their traps work, why they are almost always paired with Reflect, and how to build validation, logging, default values and a tiny reactive object.

Creating a proxy

A proxy is made from two things:

  • the target โ€” the original object being wrapped;
  • the handler โ€” an object whose methods, called traps, intercept operations.
JavaScript
const proxy = new Proxy(target, handler);

Any operation the handler doesn't trap goes straight through to the target. An empty handler gives you a proxy that behaves exactly like the target:

JS A first get trap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The get trap receives the target, the property key (a string or a symbol) and the receiver (usually the proxy itself). Whatever it returns is what the code reading the property sees.

The most useful traps

There is one trap for each fundamental operation on an object. These are the ones you will use most:

Trap Runs when codeโ€ฆ
get(target, key, receiver) reads obj.key or obj[key]
set(target, key, value, receiver) writes obj.key = value
has(target, key) checks key in obj
deleteProperty(target, key) runs delete obj.key
ownKeys(target) lists keys (Object.keys, for...in, spread)
apply(target, thisArg, args) calls a function proxy
construct(target, args) uses new on a function proxy

A set trap must return true to report success. If it returns false, the assignment fails โ€” in strict mode (and therefore in modules and classes) that throws a TypeError.

Reflect: the default behavior

Inside a trap you usually want to do something extra and then perform the normal operation. Writing target[key] works for simple cases but breaks subtle things like getters and inheritance. That is what Reflect is for.

Reflect is a plain built-in object with one method per trap, with exactly the same name and arguments: Reflect.get(), Reflect.set(), Reflect.has(), Reflect.deleteProperty(), Reflect.ownKeys(), Reflect.apply() and so on. Each one performs the default operation. So the pattern is:

JavaScript
const handler = {
  get(target, key, receiver) {
    // ...your extra logic...
    return Reflect.get(target, key, receiver); // ...then the normal behavior
  },
  set(target, key, value, receiver) {
    // ...your extra logic...
    return Reflect.set(target, key, value, receiver); // returns true or false
  },
};

Passing receiver along matters when the target has a getter that uses this: Reflect.get makes this point to the proxy, so reads inside the getter are trapped too.

Reflect is useful even without proxies. Reflect.ownKeys(obj) lists all own keys, including symbols and non-enumerable ones, and Reflect.has(obj, key) is a function version of the in operator.

Validation with a set trap

A common use is guarding an object so it can never hold bad data. Every assignment goes through the set trap, which can reject it:

JS A validating proxy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare this to custom errors and setters: a setter guards one property, while a proxy guards every property, including ones you never declared.

Logging, defaults and negative indexes

Since get runs on every read, a proxy can provide a fallback for missing properties or invent new kinds of access entirely:

JS Defaults and negative indexes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note that property keys always arrive as strings (or symbols), even for arrays: letters[-1] passes the key "-1". For negative indexes on normal arrays, modern code would simply use at(-1), but the example shows how much control a get trap gives you.

Reactive objects

The most famous use of proxies is reactivity: run some code automatically whenever data changes. The idea is simple โ€” the set trap notices every write and calls a function. Frameworks add dependency tracking on top, but the core fits in a few lines:

A tiny reactive store

The click handlers never touch the page; they only change state, and the proxy updates the screen. That is the idea that makes reactive frameworks feel like magic. A real implementation also wraps nested objects, batches several changes into one render, and tracks which parts of the page depend on which properties.

Limits and gotchas

Proxies are powerful, but keep these points in mind:

  • Only the proxy is watched. Code that holds the original target bypasses every trap. Keep the target private, as the factory functions above do.
  • Some built-ins don't like proxies. Objects with internal slots โ€” Map, Set, Date, and class instances with #private fields โ€” throw a TypeError when their methods are called through a proxy, because this is the proxy, not the real object. Workarounds exist, but they are fiddly.
  • Traps have rules (invariants). A trap can't lie about non-configurable properties; for example, get must return the real value of a frozen property. Breaking a rule throws a TypeError.
  • Proxies are slower than plain objects. That rarely matters for app state, but avoid them in hot loops.
  • Identity: proxy === target is false.

Proxy.revocable() creates a proxy you can switch off later โ€” after revoke(), every operation throws. That is handy for handing out temporary access to an object.

JavaScript
const { proxy, revoke } = Proxy.revocable({ secret: 42 }, {});
proxy.secret; // 42
revoke();
// proxy.secret now throws a TypeError

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In new Proxy(target, handler), what are the methods of handler called?

    Handler methods such as get and set are called traps because they intercept operations.
  2. 2. Why use Reflect.get(target, key, receiver) inside a get trap instead of target[key]?

    Reflect methods perform the default behavior for each operation. With receiver, getters run with this set to the proxy.
  3. 3. What must a set trap return when the assignment succeeds?

    A set trap returns a boolean. Returning false makes the assignment fail, which throws in strict mode code.
  4. 4. A proxy wraps an object, but some code changes the original object directly. What happens?

    Traps only see operations performed through the proxy. Keep the target private so all access goes through it.
  5. 5. Which trap intercepts calling a function proxy like fn(1, 2)?

    apply runs for normal calls. construct runs for new fn().

Summary

  • A Proxy wraps a target object and runs traps from its handler when code reads, writes, deletes, lists keys or calls it.
  • Untrapped operations pass straight through to the target.
  • Reflect has one method per trap that performs the default behavior; call it from your traps and pass receiver along.
  • Common uses: validation (set), defaults and computed access (get), logging and tracing (apply), and reactive state.
  • Watch the limits: the raw target bypasses traps, built-ins with internal slots and #private fields break, and invariants must hold.

Next: Typed Arrays and Binary Data.