Skip to main content

Proxy, traps

What Proxy is

Proxy is a wrapper around an object (or function) that intercepts operations on it (reading, writing, calling, and so on).

It's created like this:

javascript
const proxy = new Proxy(target, handler);
  • target is the original object (the one we want to work with);
  • handler is an object with "traps", special interceptor methods that describe how to react to different operations.

Why proxies are needed

Proxies let you intervene in an object's base behavior, for example to:

  • log access to properties;
  • validate data on write;
  • build "reactive" objects (like in Vue);
  • lazily load values;
  • protect private data.

Example: logging every access to an object:

javascript
const user = { name: "Tim", age: 25 }; const proxy = new Proxy(user, { get(target, prop) { console.log(`Reading property "${prop}"`); return target[prop]; } }); console.log(proxy.name); // Log: Reading property "name"

What the get trap does

get(target, prop, receiver) fires when a property of the object is accessed:

javascript
proxy.name; proxy["age"];

It lets you:

  • control what's returned when reading;
  • provide default values;
  • create computed properties;
  • hide certain fields.

Example:

javascript
const user = { name: "Tim" }; const proxy = new Proxy(user, { get(target, prop) { if (prop === "greet") { return `Hello, ${target.name}!`; } return target[prop] ?? "No such property"; } }); console.log(proxy.name); // "Tim" console.log(proxy.greet); // "Hello, Tim!" console.log(proxy.age); // "No such property"

What the set trap does

set(target, prop, value, receiver) fires when we assign a value:

javascript
proxy.age = 30;

It lets you:

  • validate new data;
  • forbid writes;
  • automatically transform values;
  • trigger side effects (reactivity, logging, and so on).

Example:

javascript
const user = {}; const proxy = new Proxy(user, { set(target, prop, value) { if (prop === "age" && typeof value !== "number") { throw new TypeError("Age must be a number!"); } target[prop] = value; console.log(`Property "${prop}" set to ${value}`); return true; // must return true if everything went well } }); proxy.age = 25; // Log: Property "age" set to 25 proxy.name = "Tim"; proxy.age = "a lot"; // TypeError

Summary

ComponentPurpose
Proxy(target, handler)Creates a wrapper around an object
targetThe original object
handlerAn object with traps (interceptor methods)
getIntercepts reading a property
setIntercepts writing a property

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.