• JavaScript Video Tutorials

JavaScript - Reflect.deleteProperty() Method



The Reflect.deleteProperty() provides a way to delete properties from objects. It is likely to the delete operator, but it is a method rather than an operator. Reflect.deleteProperty() returns true when the property is successfully deleted and false when the deletion fails, in contrast to the delete operator, which returns a boolean indicating whether the property was properly deleted.

The main advantage of the Reflect.deleetProperty() over the delete operator is it’s behavior when the deletion fails. If the deletion is not allowed it throws a error instead of leaving it silently.

Syntax

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

Reflect.deleteProperty( target, propertyKey )

Parameters

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

  • target − The target object on which to delete the property.

  • propertyKey − String or symbol representing the name of the property to be deleted.

Return value

This method returns a Boolean values indicating whether the property was successfully deleted or not.

Examples

Example 1

Let's look at the following example, where we are going to use the Reflect.deleteProperty() and delete the property from the object.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            a: 11,
            b: 22,
            c: 33
         };
         Reflect.deleteProperty(x, 'b');
         document.write(JSON.stringify(x));
      </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 delete a property that doesn't exist and observing the output.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            a: 1,
            b: 2,
            c: 3
         };
         document.write(Reflect.deleteProperty(x, 'd'), " < br > ");
         document.write(JSON.stringify(x));
      </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.deleteProperty() within a conditional statement.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            a: 11,
            b: 22,
            c: 33
         };
         const y = 'c';
         if (Reflect.deleteProperty(x, y)) {
            document.write(`Successfully deleted property ${y}`);
         } else {
            document.write(`Failed to delete property ${y}`);
         }
      </script>
   </body>
</html>

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

Advertisements