A Proxy in JavaScript is an object that wraps another object and allows you to intercept, monitor, or modify its behavior.
You can intercept operations like:
- reading a property (
get) - setting a property (
set) - deleting a property (
deleteProperty) - checking property existence (
has) - function calls (
apply) - object construction (
construct) - and many more…
Think of a Proxy as a middleware for objects.
✅ Basic Syntax
const proxy = new Proxy(targetObject, handler);
- targetObject → the real object you want to control
- handler → object with traps (functions that intercept operations)
🧪 Example 1: Intercepting Get Operation
const user = { name: "Teekam" };
const proxy = new Proxy(user, {
get(target, prop) {
console.log(`Getting: ${prop}`);
return target[prop];
}
});
console.log(proxy.name); // logs "Getting: name" → "Teekam"
✔ You can track property access.
🧪 Example 2: Intercepting Set Operation
const user = {};
const proxy = new Proxy(user, {
set(target, prop, value) {
if (prop === "age" && value < 0) {
throw new Error("Age cannot be negative");
}
target[prop] = value;
return true;
}
});
proxy.age = 25; // OK
proxy.age = -5; // ❌ Error
✔ Used for validation
✔ Prevent invalid writes
🧪 Example 3: Automatically log all changes
const obj = {};
const proxy = new Proxy(obj, {
set(target, prop, value) {
console.log(`Setting ${prop} = ${value}`);
target[prop] = value;
return true;
}
});
proxy.x = 10; // logs: Setting x = 10
🧪 Example 4: Proxy with Arrays
const numbers = [];
const proxy = new Proxy(numbers, {
set(target, prop, value) {
console.log(`Pushed: ${value}`);
target[prop] = value;
return true;
}
});
proxy.push(5); // "Pushed: 5"
✔ Track array modifications
⭐ Real-World Use Cases of Proxy
1️⃣ State Management (Vue.js uses Proxies internally)
Track changes in objects and update UI.
const state = new Proxy({}, {
set(target, prop, value) {
console.log(`State changed: ${prop} = ${value}`);
target[prop] = value;
return true;
}
});
2️⃣ Validation
Enforce rules before updating data.
3️⃣ Logging & Debugging
Track all reads/writes on an object.
4️⃣ Security / Access Control
Prevent unauthorized changes.
5️⃣ Auto-binding functions
Useful in frameworks.
6️⃣ Reactive Framework Internals
Vue and MobX use proxies to detect changes in objects.
⭐ Proxy vs Reflect (Important)
Proxies intercept operations, and Reflect helps forward them safely:
const proxy = new Proxy(obj, {
get(target, prop) {
console.log("read", prop);
return Reflect.get(target, prop);
}
});
✔ Best practice
✔ Prevents bugs
✔ Gives default behavior
🎯 Short Interview Answer
A Proxy in JavaScript wraps an object and allows you to intercept or customize its behavior using traps like
get,set, anddeleteProperty.
It is used for validation, logging, reactivity (like Vue.js), and access control.