What is the use of the get() method in a JavaScript Proxy object?

The get() method is one of the fundamental methods in the JavaScript Proxy object. It is used to define custom behavior for reading properties or accessing elements of an object.

When you create a Proxy object, you provide a target object and a handler object. The get() method is a part of the handler object and is called whenever a property or element of the target object is read.

The get() method takes three parameters: the target object, the property being accessed, and the receiver object. The target object is the object being proxied, the property is the name or symbol of the property being accessed, and the receiver is the object that the property is being accessed on (this can be the target object or any object that inherits from it).

The get() method returns the value of the property being accessed or throws an error if the property doesn’t exist and there is no default value specified.

Using the get() method in the handler object, you can define custom behavior for reading properties or accessing elements of the target object. For example, you can intercept property access and perform additional operations before or after returning the property value. You can also modify the property value before it is returned or return a completely different value altogether.

Here’s an example of a simple get() method implementation that logs property access and returns a default value if the property doesn’t exist:

const target = { a: 1, b: 2 };
const handler = {
  get(target, prop, receiver) {
    console.log(`Accessing property ${prop}`);
    return prop in target ? target[prop] : "default";
  },
};
const proxy = new Proxy(target, handler);
console.log(proxy.a); // logs "Accessing property a" and returns 1
console.log(proxy.c); // logs "Accessing property c" and returns "default"

In this example, the get() method intercepts property access and logs the property name before returning the actual value of the property if it exists. If the property doesn’t exist, it returns a default value of “default”.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: