Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, what happens if "delete" a property that doesn't exist?

Tags:

javascript

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.)?

like image 884
thisissami Avatar asked May 06 '13 20:05

thisissami


People also ask

What happens when we access a property that does not exist in a JS object?

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.

How will you delete the property of the object in JavaScript?

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.

Can not delete property of 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.

How does delete work in JavaScript?

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.


1 Answers

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:

  1. Let ref be the result of evaluating UnaryExpression.
  2. If Type(ref) is not Reference, return true.
  3. ...

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:

  1. If O doesn’t have a property with name P, return true.
  2. ..
like image 59
user2246674 Avatar answered Sep 26 '22 19:09

user2246674