SoFunction
Updated on 2025-04-12

Introduction to the deletion method of object property in JavaScript

In JavaScript, you can use the delete operator to delete properties in an object:


Copy the codeThe code is as follows:

var t = {a:42, b:26};
(t);//Object {a=42, b=26}
delete ;
(t);//Object {b=26}


The limitation of this property delete operation is that the delete operator can only delete all properties of the object itself, and cannot delete properties inherited from the prototype object. If you want to delete the property in the prototype object, you must explicitly obtain the prototype object and perform operations in the prototype object:


Copy the codeThe code is as follows:

var o = {x:1, y:2};
var a = (o);
= 3;
(a);//Object {z=3, x=1, y=2}
delete ;//Can NOT delete inherited property
(a);//Object {z=3, x=1, y=2}
delete ;//Can delete own property
(a);//Object {x=1, y=2}
delete a.__proto__.x;
(a);//Object {y=2}


If the property in the prototype object is deleted, all objects inherited from the prototype object will be affected.

 

For the return value of the delete operation, the following rules are followed in JavaScript:

 

1. If the delete operation is successful, return true.
2. If the delete operation has no effect (for example, the property to be deleted does not exist), it will also return true.
3. If the property you want to delete has a configurable property of false, a TypeError error will be reported in strict mode, and false will be returned in non-strict mode.
If the delete operator acts as a property of the global object, then in non-strict mode, the global object in the code can be omitted:

Copy the codeThe code is as follows:

= 42;
delete c;//equal to delete ;

It should be noted that in strict mode, the above writing method will throw a SyntaxError error.