JavaScriptHard
What are proxies in JavaScript used for?
By FrontendPro Editorial Team Updated 8/8/2026
#JavaScript
Answer
In JavaScript, a proxy is an object that acts as an intermediary between an object and the code. Proxies are used to intercept and customize the fundamental operations of JavaScript objects, such as property access, assignment, function invocation, and more.
Here's a basic example of using a Proxy to log every property access:
js
const myObject = {
name: "John",
age: 42,
};
const handler = {
get: function (target, prop, receiver) {
console.log(`Someone accessed property "${prop}"`);
return target[prop];
},
};
const proxiedObject = new Proxy(myObject, handler);
console.log(proxiedObject.name);
// Someone accessed property "name"
// 'John'
console.log(proxiedObject.age);
// Someone accessed property "age"
// 42
Use cases include:
- Property access interception: Intercept and customize property access on an object.
- Property assignment validation: Validate property values before they are set on the target object.
- Logging and debugging: Create wrappers for logging and debugging interactions with an object.
- Creating reactive systems: Trigger updates in other parts of your application when object properties change (data binding).
- Data transformation: Transforming data being set or retrieved from an object.
- Mocking and stubbing in tests: Create mock or stub objects for testing purposes, allowing you to isolate dependencies and focus on the unit under test.
- Function invocation interception: Used to cache and return the result of frequently accessed methods if they involve network calls or computationally intensive logic, improving performance.
- Dynamic property creation: Useful for defining properties on the fly with default values and avoiding storing redundant data in objects.
