Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript handler.deleteProperty() Method

Improve Article
Save Article
  • Last Updated : 27 Dec, 2022
Improve Article
Save Article

The 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 which indicates whether the property was successfully deleted.

The below examples illustrate the handler.deleteProperty() method in JavaScript:

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

javascript




<script>
    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);
      
    var f = { bar: 'baz' }    
    console.log('bar' in f)  
        
    delete f.bar  
    console.log('bar' in f) 
</script>

Output: 

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

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

javascript




<script>
    const obj = new Proxy({}, {
      deleteProperty: function(target, prop) {
        if (prop in target){
          delete target[prop]
          console.log(prop+ ' property is removed.')
          return true
        }
        else {
          console.log(prop+ ' property is not removed.')
          return false
        }
      }
    })
      
    let result
      
    obj.prop1 = 10
    console.log('prop1' in obj) 
      
    result = delete obj.prop1   
    console.log(result)    
    console.log('prop1' in obj) 
      
    result = delete obj.prop1   
    console.log(result)
</script>

Output: 

true
"prop1 property is removed."
true
false
"prop1 property is not removed."
false

We have a complete list of Javascript Functions, to check those go through the Javascript Functions Complete Reference article.

Supported Browsers: The browsers supported by the handler.deleteProperty() method are listed below: 

  • Google Chrome 49 and above
  • Edge 12 and above
  • Firefox 18 and above
  • Opera 36 and above
  • Safari  10 and above

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!