JavaScript - The delete operator

javascript

// JavaScript - The delete operator:

delete objectName.memberName

The delete operator is used to delete the property of an object.  It does not
delete a local variable or global variable.  It does nothing with local and
global variables.  It does not even throw an error.  The delete operator 
doesn't delete a property from the prototype object.  Consider the following
code:

var Employee = {
  company: 'xyz'
}
var emp1 = Object.create(Employee);
delete emp1.company
console.log(emp1.company);

The output would be xyz. Here, emp1 object has company as its prototype 
property. The delete operator doesn't delete prototype property.   The emp1 
object doesn't have company as its own property. You can test it 
console.log(emp1.hasOwnProperty('company')); //output : false. However, we can 
delete the company property directly from theEmployee object using delete 
Employee.company. Or, we can also delete the emp1 object using 
the __proto__ property delete emp1.__proto__.company.

The delete operator will remove a property from the object if it has one.  It will
not touch any of the objects in the prototype linkage.  Removing a property from
an object may allow a property from the prototype linkage to shine through.

When we use the delete operator to delete an array element, the array length is 
not affected from this. This holds even if you deleted all elements of an array using 
the delete operator.  In other words, when the delete operator removes an array 
element, that deleted element is not longer present in array. In place of value at 
deleted index undefined x 1 in chrome and undefined is placed at the index.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License