Proxies and Reflect

Topic 3 of 4 in Advanced concepts5 min readBeginnerFree course

Overview

A Proxy wraps an object and lets you step in whenever someone reads, writes or deletes its properties.

JavaScript
const target = { title: 'Proxies' };

const watched = new Proxy(target, {
  get(obj, key) {
    console.log(`Reading ${String(key)}`);
    return obj[key];
  },
});

watched.title; // logs "Reading title", returns 'Proxies'

The second argument is a handler object. Its functions — called traps — replace the normal behaviour.

Your code reads and writes state through a Proxy. The proxy’s set trap can validate and log, and its get trap can return defaults or computed values. Each trap then uses Reflect.set or Reflect.get to perform the normal operation on the target object.

The proxy looks and behaves like the original object to everyone using it. Any operation without a trap passes straight through to the target unchanged.

Common traps

Trap Runs for
get(target, key, receiver) reading proxy.key
set(target, key, value, receiver) proxy.key = value
has(target, key) key in proxy
deleteProperty(target, key) delete proxy.key
ownKeys(target) Object.keys(proxy), for…in
apply(target, thisArg, args) calling a proxied function

Keys can be strings or symbols, which is why the examples use String(key) before printing.

Validation

JavaScript
const profile = new Proxy({}, {
  set(obj, key, value) {
    if (key === 'age' && !Number.isInteger(value)) {
      throw new TypeError('Age must be a whole number');
    }
    obj[key] = value;
    return true; // tell JavaScript the assignment succeeded
  },
});

profile.age = 30;     // fine
profile.age = 'old';  // TypeError: Age must be a whole number

A set trap must return true. Returning false (or nothing) means “the assignment failed”, which throws a TypeError in strict mode.

Default values

A get trap can answer for properties that don’t exist:

JavaScript
const withDefaults = (obj, fallback) =>
  new Proxy(obj, {
    get: (target, key) => (key in target ? target[key] : fallback),
  });

const counts = withDefaults({}, 0);
counts.apples++;   // no need to check for undefined first
counts.apples;     // 1
counts.pears;      // 0

Reflect

Reflect has a method for each trap that performs the default behaviour. Using it inside traps keeps edge cases (like getters and inheritance) working correctly:

JavaScript
const logged = new Proxy(target, {
  set(obj, key, value, receiver) {
    console.log('set', key);
    return Reflect.set(obj, key, value, receiver);
  },
});

Reflect.set also returns true or false, so you can return its result directly from the trap. The pairs line up one to one: get ↔ Reflect.get, has ↔ Reflect.has, deleteProperty ↔ Reflect.deleteProperty, and so on.

Reflect is useful outside proxies too — Reflect.ownKeys(obj) lists every own key, including symbols.

A tiny reactive store

This is the core idea behind frameworks like Vue: change the data, and the page updates itself.

JavaScript
function reactive(data, onChange) {
  return new Proxy(data, {
    set(target, key, value, receiver) {
      const ok = Reflect.set(target, key, value, receiver);
      onChange(key, value);
      return ok;
    },
  });
}

const state = reactive({ count: 0 }, () => {
  counterEl.textContent = state.count;
});

button.addEventListener('click', () => {
  state.count++; // the page updates automatically
});

Things to know

  • Proxies only intercept operations done through the proxy. Code holding the original target bypasses the traps entirely — so usually you keep only the proxy.
  • They’re shallow: a nested object read through a proxy is the plain nested object, unless your get trap wraps it too.
  • Some built-in objects, like Map and Date, use internal slots that don’t work through a simple proxy.

Where you’ll meet them

Frameworks such as Vue use proxies to notice when your data changes and update the page automatically. Testing libraries use them to create mock objects, and some libraries use them to give friendly error messages for misspelled properties.

Use sparingly. Proxies add a little overhead and can make code surprising to read. Plain functions and classes are usually enough.

Exercise

Log every change

Wrap state in a Proxy that logs key → value whenever a property is set. Then add a get trap that returns 0 for any property that doesn’t exist.

JavaScript
const state = { count: 0 };

Summary

  • A Proxy wraps an object and lets you intercept operations on it.
  • Handler functions (traps) such as get, set, has and deleteProperty run instead of the default.
  • A set trap must return true for success.
  • Reflect performs the default behaviour from inside a trap.
  • Proxies power validation, logging, defaults and reactive frameworks — use them sparingly.