What happens in JavaScript if I have a variable, say:
var exampleObject = {one:'foo',two:'bar'};
and then I delete a property that doesn't exist, a la:
delete exampleObject.seven;
Is there a standard course of action that takes place everywhere (nothing, error message, script crashes, etc.), or is this dependent on some kind of implementation (browser engine, etc.)?
If a property does not exist in the object, it returns false . Unlike the hasOwnProperty() method, the in operator looks for the property in both own properties and inherited properties of the object.
Answer: Use the delete Operator You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.
You can only delete a Property or Method of an object using the Delete Operator. It will completely remove the Property from the collection. It also does not remove the Non-configurable properties. Delete returns false if the property is an own property and cannot be deleted.
The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
Nothing happens.
Assuming, x = {}
, Type(x.y)
is not a Reference Specifcation Type (there cannot be a "reference" to a property that does not exist). According to 11.4.1 The delete Operator, this satisfies the rule:
- Let ref be the result of evaluating UnaryExpression.
- If Type(ref) is not Reference, return true.
- ...
This behavior (of "no action") has existed for a long time - any environment that behaves differently is non-compliant. From the 3rd Edition ECMAScript Specification:
When the [[Delete]] method of O is called with property name P, the following steps are taken:
- If O doesn’t have a property with name P, return true.
- ..
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