handler.deleteProperty()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.
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
new Proxy(target, {
deleteProperty(target, property) {
}
})
Parameters
Return value
The deleteProperty()
method must return a Boolean
indicating whether or not the property has been successfully deleted. Other values are coerced to booleans.
Many operations, including the delete
operator when in strict mode, throw a TypeError
if the [[Delete]]
internal method returns false
.
Description
Interceptions
This trap can intercept these operations:
- The
delete
operator:delete proxy[foo]
anddelete proxy.foo
Reflect.deleteProperty()
Or any other operation that invokes the [[Delete]]
internal method.
Invariants
The proxy's [[Delete]]
internal method throws a TypeError
if the handler definition violates one of the following invariants:
- A property cannot be reported as deleted, if it exists as a non-configurable own property of the target object. That is, if
Reflect.getOwnPropertyDescriptor()
returnsconfigurable: false
for the property ontarget
, then the trap must return a falsy value. - A property cannot be reported as deleted, if it exists as an own property of the target object and the target object is non-extensible. That is, if
Reflect.isExtensible()
returnsfalse
ontarget
, andReflect.getOwnPropertyDescriptor()
returns a property descriptor for the property ontarget
, then the trap must return a falsy value.
Examples
Trapping the delete operator
The following code traps the delete
operator.
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