Javascript delete Operator

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.

When using the delete operator on arrays take caution as delete will delete the specified item but the array length not get affected.

 

Let’s take an example

In the code above we defined an object with two items and then displayed the “firstname” property in the console. Next i delete the “firstname” property as shown above after that when displaying the property again it shows “undefined”.

 

delete operator will return true for all cases except when the property is an own non-configurable property, in which case, false is returned in non-strict mode.

 

delete operator Exceptions

The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned. However, it is important to consider the following scenarios:

  • If the property which you are trying to delete does not exist, delete will not have any effect and will return true
  • If a property with the same name exists on the object’s prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).
  • Any property declared with var cannot be deleted from the global scope or from a function’s scope.
  • Any property declared with let or const cannot be deleted from the scope within which they were defined.
  • Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().

The following snippet gives a simple example:

 

Non-configurable properties

When a property is marked as non-configurable, delete won’t have any effect, and will return false. In strict mode this will raise a SyntaxError.

var, let and const create non-configurable properties that cannot be deleted with the delete operator:

 

Share this: