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!

Top comments (0)