JavaScript Tutorial JavaScript Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

JavaScript - delete operator



The JavaScript delete operator removes a property from an object. If no more references to the same property are found, it is eventually released automatically. The syntax for using this operator is given below:

Syntax

delete object.property
delete object['property']

However, it is important to consider the following scenarios:

  • If the property 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.
    • As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function expression).
    • Functions which are part of an object (apart from the global scope) can be deleted with delete.
  • 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().

Parameters

object Specify the name of an object, or an expression evaluating to an object.
property Specify the property to delete.

Return Value

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

Exceptions

Throws TypeError in strict mode if the property is an own non-configurable property.

Example:

In the example below, the delete operator is used to find the datatype of a given variable or expression.

var Person = { 
  name: 'John', 
  age: 25, 
  city: 'London' 
}

//returns true
document.write("delete Person.name : ", (delete Person.name), "<br>");
//returns true
document.write("delete Person['age'] : ", (delete Person['age']), "<br>");
//When trying to delete a property that
//does not exist, true is returned
document.write("delete Person.hobby : ", (delete Person.hobby), "<br>");

The output (value of txt) after running above script will be:

delete Person.name : true
delete Person['age'] : true
delete Person.hobby : true

❮ JavaScript - Operators

5