Exploring the Fundamentals of Proxy and Reflect API in JavaScript 2023

Exploring the Fundamentals of Proxy and Reflect API in JavaScript 2023

A Proxy allows you to wrap and intercept methods and properties of other objects.

Introduction

Hi, Dev's Modern JavaScript is amazing. There are so many features you might not have had a chance to use and some that are probably being utilized by some of your favorite frameworks and tooling.One such feature is the Proxy.

Today we are going to explore the features of proxy & how it's used on popular frameworks like vue3 to build their own reactivity system.

Proxy

A Proxy allows you to wrap and intercept methods and properties of other objects. You might want to validate data or simply notify parts of your application when some change to the Proxy object has occurred.

Proxy gets its name because it acts as the Proxy or middle-man for your target object and your handlers.

Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.


Let deep dive

The example may not looks more realestic but bear with me to understand proxy API better. Now think that you want to track a change in an object and How many times the object got changed.

You may get an idea to write a function with its keys. If the key changes call a function to increase a global count variable. That is a ton of manual work & hard to maintain a code in the long run.

That's where the javascript proxy API comes into the picture. It helps us to intersect the object changes.The classic example can be you have an object you want to convert the values of object value to upper case id its type string.

const handler = {
    get(target, prop) {
        // always return in UPPERCASE
        return target[prop]?.toUpperCase();
    },
    set(target, prop, value) {
        if (typeof value !== "string") {
            throw new Error("Value can only be string!");
        }
        target[prop] = value;
        return true;
    }
}

const user = new Proxy({}, handler);
user.name = "Saravana"
user.age = 23; // throws an error, but change to user.age = "23" and it will work.

// Set property correctly
user.name = "Saravana"
user.age = "23";

console.log(user.name); // SARAVANA

Now you may get a better understanding of Proxy API in javascript. Now you may have a question where doest it used?

Uses of Proxy API

A Proxy API in JavaScript feature was introduced in ECMAScript 6 (ES6) and is quite powerful for various use cases. Here are some common uses of Proxy API in JavaScript.

  • Validation and Data Integrity

  • Logging and Debugging

  • Memoization and Caching

  • Immutable Data Structures

This feature is used to build the core reactivity system of Vue3 js. Checkout the source code of vue3.

Reflect API

The Reflect namespace object contains static methods for invoking interceptable JavaScript object internal methods. The methods are the same as those of proxy handlers.

Simple terms

The Reflect object allows you to use the default behavior of the object in a Proxy. This means that if you come across a function in your handlers getter that you are not concerned with, you can use Reflect to use the default behavior of that object.

// A slightly modified version of our earlier example
const handler = {
    get(target, prop) {
        if (typeof target[prop] === "function") {
            // Any functions can easily forward their
            // default implementation using Reflect
            return Reflect.get(target, prop);
        }
        // always return in UPPERCASE
        return target[prop]?.toUpperCase();
    },
    set(target, prop, value) {
        if (typeof value !== "string") {
            throw new Error("Value can only be string!");
        }
        target[prop] = value;
        return true;
    }
}

const user = new Proxy({}, handler);
user.name = "Saravana"
user.age = "23";
console.log(user.hasOwnProperty("address")); // false

In this snippet, we are trying to access the native hasOwnProperty method of the object. We are not interested in intercepting this method, so we can use Reflect to use the default behavior.

There are a number of methods available in the Reflect object that can be used with Proxy objects, or any other objects. We won’t dive into details on these. For now, we’ve laid the foundation to really get some powerful use from Proxy.

Conclusion

The Proxy API in JavaScript is a powerful feature that allows you to intercept and customize operations on objects, such as property access, assignment, function invocation, and more.

I am excited to hear your thoughts & Please take a moment to share your thoughts and share them with your friends.

Did you find this article valuable?

Support Saravana Sai by becoming a sponsor. Any amount is appreciated!