JavaScript Proxy

JavaScript Proxy

Proxy is used in many libraries and frameworks.

It is a powerful tool that allows you to rewrite reality inside your code.

For example, in other languages, you can use a negative index to get array elements. But it’s not allowed in JavaScript.

l = [1,2,3]
l[-1] //3

You can make it happen with Proxy.

let arr = [1,2,3]
arr = new Proxy(arr, customHandler);
arr[-1] //3

So how does it work?

Every object has default methods like get and set.

When you access an array, internally, JavaScript is calling a get method on the array object.

To change the default behaviours, you wrap the array object with a proxy and a custom handler.

Here’s how to do it.

Create a proxy.

Pass in the object you want to change, and your custom handler.

arr = new Proxy(arr, customHandler);

To access the array with a negative index, you need a handler for the get method. If you return 0 here, for example, getting any items from the array will return a value of zero.

arr = new Proxy(arr, {
  get(target, prop, _) {
    return 0
  }
});

The get method takes three arguments.

array = new Proxy(array, {
  get(target, prop, _) {

});

The first is the array itself. The second is the property, in this case, the index. The third is not relevant for now.

Let's implement the logic.

array = new Proxy(array, {
  get(target, prop, _) {
    if (prop < 0) {
      prop = +prop + target.length;
    }
    return target[prop]
  }
});

If the index is negative, replace it with the corresponding positive index. For example, -1 will become 2.

If the index is positive, we don't have to do anything.

Finally, return the correct array value.

Now, you can use a negative index to get array items in JavaScript.

Level up your javascript, one step at a time.

Get the written notes delivered to your email inbox to learn something new about javascript one at a time.