What is Proxy in JavaScript: Simple Explanation and Example
Proxy is an object that wraps another object and lets you control or customize fundamental operations like reading, writing, or deleting properties. It acts like a middleman that intercepts actions on the original object, allowing you to add extra behavior or validation.How It Works
Imagine you have a mailbox, and you want to control who can put letters in or take letters out. A Proxy acts like a guard standing in front of the mailbox, checking every action before it happens. When you try to get or set a property on an object, the proxy intercepts that action and can decide what to do with it.
This means you can add rules or extra steps whenever someone tries to interact with the object. For example, you can log every time a property is read or prevent certain properties from being changed. The proxy uses special functions called traps to catch these actions and handle them.
Example
This example shows a proxy that logs every time a property is read or changed on an object.
const person = { name: 'Alice', age: 25 }; const handler = { get(target, property) { console.log(`Getting ${property}`); return target[property]; }, set(target, property, value) { console.log(`Setting ${property} to ${value}`); target[property] = value; return true; } }; const proxyPerson = new Proxy(person, handler); console.log(proxyPerson.name); proxyPerson.age = 26; console.log(proxyPerson.age);
When to Use
Use a Proxy when you want to add extra control or behavior to an object without changing its original code. Common uses include:
- Validating data before setting properties
- Logging or debugging property access
- Creating default values for missing properties
- Implementing reactive programming patterns (like in some frameworks)
For example, if you want to make sure a user’s age is always a positive number, you can use a proxy to check that before allowing the change.
Key Points
- A
Proxywraps an object and intercepts operations on it. - It uses traps like
getandsetto customize behavior. - Proxies help add validation, logging, or default behaviors easily.
- They are powerful for building flexible and reactive code.