0
0
JavascriptConceptBeginner · 3 min read

What is Proxy in JavaScript: Simple Explanation and Example

In JavaScript, a 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.

javascript
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);
Output
Getting name Alice Setting age to 26 Getting age 26
🎯

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 Proxy wraps an object and intercepts operations on it.
  • It uses traps like get and set to customize behavior.
  • Proxies help add validation, logging, or default behaviors easily.
  • They are powerful for building flexible and reactive code.

Key Takeaways

A Proxy lets you control how an object’s properties are accessed or changed.
Use traps like get and set to add custom behavior on property access.
Proxies are useful for validation, logging, and reactive programming.
They act as a middleman between your code and the original object.