What is Proxy Object in JavaScript
Proxy is a built-in object in JavaScript that allows intercepting and redefining behavior of other objects. You can "wrap" an object and control access to its properties, their modification, deletion, function calls and much more.
Simply put, Proxy is like a "layer" between object and its usage.
Syntax
const proxy = new Proxy(target, handler);
target— object you're wrapping.handler— object with interceptor functions (so-called "traps"), e.g.:get,set,has,deleteProperty.
Example: logging property access
const user = { name: "Alice", age: 25 };
const proxy = new Proxy(user, {
get(target, prop) {
console.log(`Reading property "${prop}"`);
return target[prop];
},
});
console.log(proxy.name); // Reading property "name" → "Alice"
Commonly Used Traps
| Trap | Description |
|---|---|
get() | Reading property |
set() | Writing value to property |
has() | in operator |
deleteProperty() | Deleting property (delete) |
apply() | Function call |
construct() | Call via new |
defineProperty() | Working with Object.defineProperty() |
getOwnPropertyDescriptor() | Getting property descriptor |
Example: value validation
const user = {
name: "Alice",
age: 25
};
const validatedUser = new Proxy(user, {
set(target, prop, value) {
if (prop === "age" && typeof value !== "number") {
throw new TypeError("Age must be a number");
}
target[prop] = value;
return true;
}
});
validatedUser.age = 30; // OK
validatedUser.age = "много"; // Error
When to Use Proxy
- For data reactivity (Vue, MobX)
- For validation and logging
- For creating dynamic APIs
- For adding meta-information when accessing objects
- For catching errors or protecting object from misuse