Hiprup

What are Proxy and Reflect in JavaScript?

Proxy and Reflect let you intercept and customise fundamental operations on objects.

  • Proxy — wraps an object and traps operations (get, set, has, deleteProperty…) so you can run custom logic.

  • Reflect — a companion with methods that perform the default operations, used inside traps to keep standard behaviour.

Real-world uses: validation, logging, default values, and reactive frameworks — Vue's reactivity is built on Proxy.

// Validation proxy
const validator = {
  set(target, prop, value) {
    if (prop === 'age' && (typeof value !== 'number' || value < 0)) {
      throw new TypeError('Age must be a positive number');
    }
    target[prop] = value;
    return true;
  },
  get(target, prop) {
    return prop in target ? target[prop] : `Property '${prop}' not found`;
  }
};

const user = new Proxy({}, validator);
user.name = 'John';       // OK
user.age = 30;             // OK
// user.age = -5;           // TypeError!
console.log(user.unknown); // "Property 'unknown' not found"

// Logging proxy
function createLogger(obj) {
  return new Proxy(obj, {
    get(target, prop, receiver) {
      console.log(`GET ${String(prop)}`);
      return Reflect.get(target, prop, receiver);
    },
    set(target, prop, value, receiver) {
      console.log(`SET ${String(prop)} = ${value}`);
      return Reflect.set(target, prop, value, receiver);
    }
  });
}

const logged = createLogger({ x: 1 });
logged.x;     // logs: GET x
logged.y = 2; // logs: SET y = 2

The validator proxy rejects invalid age values on set and returns descriptive messages for missing properties on get. The logging proxy uses Reflect to perform the default operation while adding logging.

Reflect.get/set provide the standard behavior that would occur without the Proxy.

Show a practical example (validation or logging). Know that Reflect provides default behavior for each trap.

Vue 3 using Proxy for reactivity is a real-world connection. Proxy enables meta-programming — intercepting fundamental operations.

What are Proxy and Reflect in JavaScript? | Hiprup