JS Meta & Proxy

Meta programming enables dynamic behavior at runtime. Understand Proxy and Reflect for advanced object control.

On this page

Meta Programming

Meta programming means writing code that can inspect or modify the behavior of other code at runtime. In JavaScript, this is mainly done using Reflect and Proxy.

Common meta-programming use cases:

  • Validation layers
  • Logging and debugging
  • Access control
  • Reactive frameworks (like Vue)

Meta Reflect

The Reflect object provides methods that mirror many internal object operations. It offers a cleaner and more consistent API than older Object methods.

const user = { name: "Ozan" };

Reflect.set(user, "age", 30);
console.log(Reflect.get(user, "name"));

console.log(Reflect.has(user, "age"));
Reflect.deleteProperty(user, "age");

Reflect methods return booleans instead of throwing errors in some cases, which makes them safer in advanced logic.

Meta Proxy

A Proxy wraps an object and intercepts operations like reading, writing, deleting, or calling functions.

const target = { name: "Jane" };

const handler = {
  get(obj, prop) {
    console.log("Getting property:", prop);
    return obj[prop];
  },
  set(obj, prop, value) {
    console.log("Setting", prop, "to", value);
    obj[prop] = value;
    return true;
  }
};

const proxy = new Proxy(target, handler);

console.log(proxy.name);
proxy.age = 25;

Common traps:

  • get
  • set
  • has
  • deleteProperty
  • apply (for functions)
  • construct (for constructors)

Validation Example

const person = {
  name: "Ali",
  age: 20
};

const validated = new Proxy(person, {
  set(obj, prop, value) {
    if (prop === "age" && typeof value !== "number") {
      throw new TypeError("Age must be a number");
    }
    obj[prop] = value;
    return true;
  }
});

validated.age = 30;
// validated.age = "thirty"; // throws error

Function Proxy

function sum(a, b) {
  return a + b;
}

const proxiedSum = new Proxy(sum, {
  apply(target, thisArg, args) {
    console.log("Called with:", args);
    return Reflect.apply(target, thisArg, args);
  }
});

console.log(proxiedSum(2, 3));

Meta Reference

Key meta-programming tools:

  • Reflect.get()
  • Reflect.set()
  • Reflect.has()
  • Proxy constructor
  • Proxy traps: get, set, apply, construct

Important notes:

  • Proxy cannot be partially applied — once wrapped, all access goes through it.
  • Proxy affects performance; avoid unnecessary usage in hot paths.
  • Frameworks like Vue use Proxy for reactivity systems.

Next Step

Continue with JS Typed Arrays or JS Web APIs depending on your use case.

JS Meta & Proxy Examples (8)