handler.deleteProperty()

The handler.deleteProperty() method is a trap for the [[Delete]] object internal method, which is used by operations such as the delete operator.

Try it

Syntax

js
new Proxy(target, {
  deleteProperty(target, property) {
  }
});

Parameters

The following parameters are passed to the deleteProperty() method. this is bound to the handler.

target

The target object.

property

The name or Symbol of the property to delete.

Return value

The deleteProperty() method must return a boolean value indicating whether or not the property has been successfully deleted.

Description

Interceptions

This trap can intercept these operations:

Or any other operation that invokes the [[Delete]] internal method.

Invariants

If the following invariants are violated, the trap throws a TypeError when invoked.

  • A property cannot be deleted, if it exists as a non-configurable own property of the target object.

Examples

Trapping the delete operator

The following code traps the delete operator.

js
const p = new Proxy(
  {},
  {
    deleteProperty(target, prop) {
      if (!(prop in target)) {
        console.log(`property not found: ${prop}`);
        return false;
      }
      delete target[prop];
      console.log(`property removed: ${prop}`);
      return true;
    },
  },
);

p.a = 10;
console.log("a" in p); // true

const result1 = delete p.a; // "property removed: a"
console.log(result1); // true
console.log("a" in p); // false

const result2 = delete p.a; // "property not found: a"
console.log(result2); // false

Specifications

Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-delete-p

Browser compatibility

BCD tables only load in the browser

See also