The behaviour of the delete operator seems very complicated and there are many misunderstandings about what it actually does. To me, it seems that reassigning something to undefined
will more reliably do what you would expect.
I've never seen the delete
keyword in Javascript actually used in non-example code and I am wondering if it is particularly useful for anything. Does delete
have any purpose that cannot be acheived by reassignment to undefined
? Is it used at all in any of the famous libraries (e.g. jQuery, dojo, backbone, etc)?
Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. New operator is used for dynamic memory allocation which puts variables on heap memory.
Explanation: The delete operator is the reverse process of a new operator. It deallocates all the memory allocated for an object. The object can be of any type. The delete operator completely destroys an object so that the resources can be used for other purposes.
The delete keyword deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.
Since JavaScript arrays are objects, elements can be deleted by using delete . delete will delete the object property, but will not reindex the array or update its length. This makes it appear as if it is undefined . Using delete may leave undefined holes in the array.
Does delete have any purpose that cannot be acheived by reassignment to undefined?
Yes. If you want to unmask a property from a prototype or cause in
, hasOwnProperty
, and for (...in...)
to not record the property as existing then delete
is appropriate.
let set = {}; set._x = true; alert('_x' in set); // true set._x = undefined; alert('_x' in set); // true delete set._x; alert('_x' in set); // false
EDIT: As T.J. Crowder explains:
The purpose of the
delete
operator is to completely remove a property from an object, whereas setting a property toundefined
just sets the property toundefined
.This matters in its own right, but it also matters when you're using inheritance, because if O derives from P
let P = { prop: 42 }; let O = Object.create(P); // P is O's prototype.
when you retrieve
O.prop
, you get the value of prop from O if O has a property with that name (even if its value is undefined), but if O doesn't have the property at all, then the value will be retrieved fromP.prop
instead.
console.log(O.prop); // "42" since O doesn't have its own prop, but P does. O.prop = undefined; console.log(O.prop); // "undefined" since O has its own prop. delete O.prop; console.log(O.prop); // "42" since the delete "unmasked" P.prop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With