• JavaScript Video Tutorials

JavaScript - Reflect.set() Method



The Reflect.set() method allows you to set the value of a property on an object.. Unlike Object.defineProperty() or the assignment operator, Reflect.set() also works with proxies and respects their handlers. This method is useful in situations when you need to make sure that the handler's set trap is triggered or when you need to dynamically set the value of a property.

In situations, where you need to verify whether a property was set properly, the Reflect.set() method offers a more adaptable and clear manner of setting properties on objects.

Syntax

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

Reflect.set(obj, Key, value, receiver) 

Parameters

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

  • obj − The target object on which to set the property.

  • Key − Indicates the name of the property to hold.

  • value − The value to be set.

  • receiver − It's a optional parameter and the value of this is provided for the call to the target.

Return value

This method returns a Boolean value indicating whether the property was successfully set or not.

Examples

Example 1

Let's look at the following example, where we are going to use the Reflect.set() method to set the property to the object.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {};
         Reflect.set(x, 'val', 12345);
         document.write(x.val);
      </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 use the symbol as a property key.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {};
         const y = Symbol();
         Reflect.set(x, y, 'Welcome');
         document.write(x[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 set a Property on an array.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         let x = ['Lion', 'Tiger', 'Deer'];
         Reflect.set(x, 1, 'Elephant');
         document.write(JSON.stringify(x));
      </script>
   </body>
</html>

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

Advertisements