How to delete any property of a targeted obect using the handler.deleteProperty() method

JavaScript handler.deleteProperty() method in JavaScript is a trap for the delete operator. This method returns the boolean value if the delete was successful.

Syntax: 

const p = new Proxy(target, {
      deleteProperty: function(target, property) {
  }
});

Parameters: This method accepts two parameters as mentioned above and described below: 

  • Target: This parameter holds the target object.
  • Property: This parameter holds the name of the property which is to be deleted.

Return value: This method returns a Boolean value that indicates whether the property was successfully deleted.

Example 1: In this example, we will trap a delete operator using the handler.deleteProperty() method in JavaScript.

const monster1 = {

Color: ‘Green’

};

const handler1 = {

deleteProperty(target, prop) {

if (prop in target) {

delete target[prop];

console.log(`${prop} is property which is removed`);

}

}

};

console.log(monster1.Color);

const proxy1 = new Proxy(monster1, handler1);

delete proxy1.Color;

console.log(monster1.Color);

let f = { bar: ‘baz’ }

console.log(‘bar’ in f)

delete f.bar

console.log(‘bar’ in f)

Output: 

"Green"
"Color is property which is removed"
undefined
true
false

Leave a comment

Your email address will not be published. Required fields are marked *