DEV Community

Quan Nguyen
Quan Nguyen

Posted on

Reflect in Javascript

Reflect in JavaScript is a built-in object that provides methods for interacting with objects and the underlying runtime. It allows you to perform common operations on objects such as setting and getting property values, checking for the existence of a property, and calling functions, among others.

One of the main benefits of using the Reflect object is that it provides a consistent way to perform these operations, which can often be performed in multiple ways using other JavaScript features. For example, you can use the Reflect.get method to get a property value, which is equivalent to using the square bracket notation ([]) or the dot notation (.).

Here's an example of using the Reflect.get method:

const object = { name: "John Doe" };
console.log(Reflect.get(object, "name"));

Enter fullscreen mode Exit fullscreen mode

In this example, the Reflect.get method is used to get the value of the name property on the object.

Another useful feature of the Reflect object is the Reflect.apply method, which allows you to call a function as if it were a method of an object. This can be useful when working with functions that are not attached to an object, but you still want to call them with a specific this value.

Here's an example of using the Reflect.apply method:

const sum = (a, b) => a + b;
console.log(Reflect.apply(sum, null, [1, 2]));
Enter fullscreen mode Exit fullscreen mode

In this example, the Reflect.apply method is used to call the sum function with a this value of null and arguments [1, 2].

In conclusion, the Reflect object in JavaScript provides a convenient and consistent way to perform common operations on objects, such as getting and setting property values, checking for the existence of a property, and calling functions. Whether you are writing a complex web application or a simple utility, the Reflect object can be a useful tool for interacting with objects and the underlying runtime.

Top comments (0)