JavaScript Proxies

In JavaScript, proxies (proxy object) are used to wrap an object and redefine various operations into the object such as reading, insertion, validation, etc. Proxy allows you to add custom behavior to an object or a function.


Creating a Proxy Object

The syntax of proxy is:

new Proxy(target, handler);

Here,

  • new Proxy() - the constructor.
  • target - the object/function which you want to proxy
  • handler - can redefine the custom behavior of the object

For example,

Here, the get() method is used to access the object's property value. And if the property is not available in the object, it returns property does not exist.

As you can see, you can use a proxy to create new operations for the object. A case may arise when you want to check if an object has a particular key and perform an action based on that key. In such cases, proxies can be used.

You can also pass an empty handler. When an empty handler is passed, the proxy behaves as an original object. For example,


Proxy handlers

Proxy provides two handler methods get() and set().

get() handler

The get() method is used to access the properties of a target object. For example,

Here, the get() method takes the object and the property as its parameters.


set() handler

The set() method is used to set the value of an object. For example,

Here, a new property age is added to the student object.


Uses of Proxy

1. For Validation

You can use a proxy for validation. You can check the value of a key and perform an action based on that value.

For example,

Here, only the name property of the student object is accessible. Else, it returns Not allowed.


2. Read Only View of an Object

There may be times when you do not want to let others make changes in an object. In such cases, you can use a proxy to make an object readable only. For example,

In the above program, one cannot mutate the object in any way.

If one tries to mutate the object in any way, you'll only receive a string saying Read Only.


3. Side Effects

You can use a proxy to call another function when a condition is met. For example,


JavaScript proxy was introduced from the version of JavaScript ES6. Some browsers may not fully support its use. To learn more, visit JavaScript proxy.