DEV Community

zain ul abdin
zain ul abdin

Posted on

The Power of Proxy

Proxy object is one of the most powerful yet underused features in JavaScript!

It allows you complete control over how your objects behave in JavaScript by defining custom behavior for basic operations on objects, like getting or setting properties.

It can also be used to create custom validation, data binding, logging, or even create fully reactive objects—without needing a library!

Here’s a simple example:

const user = {
  name: 'Zain',
  age: 22
};

const handler = {
  get: (target, prop) => {
    console.log(`Getting property ${prop}`);
    return prop in target ? target[prop] : 'Property does not exist';
  },
  set: (target, prop, value) => {
    if (prop === 'age' && typeof value !== 'number') {
      console.log('Invalid age type. It should be a number.');
    } else {
      console.log(`Setting property ${prop} to ${value}`);
      target[prop] = value;
    }
    return true;
  }
};

const proxiedUser = new Proxy(user, handler);

console.log(proxiedUser.name); // Logs: Getting property name
proxiedUser.age = 'twenty-two'; // Logs: Invalid age type. It should be a number.
proxiedUser.age = 23; // Logs: Setting property age to 23

Enter fullscreen mode Exit fullscreen mode

With Proxy, you can intercept and redefine almost any fundamental behavior for objects—adding a layer of control and customization that's unmatched by any other feature in JavaScript!


To stay updated with more content related to web development and AI, feel free to follow me. Let's learn and grow together!

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay