• JavaScript Video Tutorials

JavaScript - Reflect.getOwnPropertyDescriptor() Method



The Reflect.getOwnPropertyDescriptor() method allows you to retrieve the property descriptor of a given property on an object. It provides the detailed information about the property, such as its configurable, enumerable, and writable nature. Compared to Object.getOwnPropertyDescriptor(), this method, which is a component of the Reflect object, offers a more flexible and consistent approach to access property descriptors. It can be particularly useful in meta-programming scenarios, enabling dynamic property manipulation.

Syntax

Following is the syntax of JavaScript Reflect.getOwnPropertyDescriptor() method −

Reflect.getOwnPropertyDescriptor(target, propertyKey)

Parameters

This method accepts two parameters. The same are described below −

  • target − The object on which to retrieve the property descriptor.

  • propertyKey − Name of the property whose descriptor you want to retrieve.

Return value

This method returns the property descriptor of the property on the object. If the property doesn't exist, it returns undefined.

Examples

Example 1

Let's look at the following example, where we are going to retrieve the property descriptor of the property car from the object.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         let x = {
            car: 'RS6'
         };
         let y = Reflect.getOwnPropertyDescriptor(x, 'car');
         document.write(JSON.stringify(y));
      </script>
   </body>
</html>

If we execute the above program, it will displays a text on the webpage.

Example 2

Consider another scenario where we are going to get a non-enumerable property descriptor.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         let x = {};
         Object.defineProperty(x, 'Tp', {
            value: 'Welcome',
            enumerable: false
         });
         let y = Reflect.getOwnPropertyDescriptor(x, 'Tp');
         document.write(JSON.stringify(y));
      </script>
   </body>
</html>

On executing the above script, it will displays a text on the webpage.

Example 3

In the following example, we are going to use the Reflect.getOwnPropertyDescriptor() method on the non-existent property.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {};
         const y = Reflect.getOwnPropertyDescriptor(x, 'Tp');
         document.write(JSON.stringify(y));
      </script>
   </body>
</html>

When we execute the above script, the output window will pop up, displaying the text on the webpage.

Advertisements