Delete Operator in JavaScript

Learn How to Delete Property from Object using the Delete Operator. The Delete Operator can be used to delete own property of an object or an element from an array.

Delete Operator

You can delete a Property from an Object using the Delete Operator. The Syntax of the delete operator is as shown below

delete object.property
delete object['property']

Where

  1. object is the name of an object, or an expression evaluating to an object. Note that expression must evaluate to a object
  2. property is the property to delete.

Note that

  1. You can delete a Property or Method of an object using the Delete Operator. It will completely remove the Property from the collection.
  2. Delete Operator can also be used to delete a array element. But this will not re arrange the array, but converts it into an sparse array
  3. Delete will not delete the regular variables or functions
  4. You can only delete the property owned by the object. You cannot delete the inherited properties (i.e. Prototype Properties)
  5. It also does not remove the Non-configurable properties.
  6. Delete returns false if the property is an own property and cannot be deleted. In all other cases it returns true.

Try to Avoid adding or deleting the Property of an object after it is created. The JavaScript engines optimize the performance of instances created by constructors. Adding or deleting prevents that optimization

Delete Property from Object

In the following example, we use the delete operator to delete the foo property the object obj.

The delete will remove the property from the collection. Hence you will not see the property when using the console.log on obj

let obj = {
    foo:'1',
    boo:'2'
}

console.log(obj)  //{foo: "1", boo: "2"}
delete obj.foo    //deleting foo
console.log(obj)   //{boo: "2"}   //foo is deleted

Deletes Only Own Properties

Delete Only deletes the own properties. It does not delete the inherited properties.

The own property is a property that we declare directly on the object. The objects can also inherit properties from their prototype object. You can check if a property is an own property or not by using the hasOwnProperty method

The following example, create a obj1 from the constructor function obj. Here foo & boo are the own properties of the obj1. It does not define toString but inherits it from its Prototype. Hence we cannot delete it.

Another interesting point to note that the delete operator returns true, although it does not delete anything.

function obj() {
    this.foo=1
    this.boo=2
}

obj1 = new obj()
console.log(obj1)         //obj { foo: 1, boo: 2 }
console.log(obj1.hasOwnProperty('foo'))   //true
delete obj1.foo      //deleting foo
console.log(obj1)    // obj {boo: 2}    foo is deleted

console.log(obj1.hasOwnProperty('toString'))   //false
var result=delete obj1.toString   //deleting toString
console.log(result)               //true
console.log(obj1.toString())      //still works. 
//It does not delete toString. Because it is not own property of Obj1

The toString function belongs to the Object.prototype. Hence we can delete it from there.

function obj() {
    this.foo=1
    this.boo=2
}
obj1 = new obj()

console.log(obj1.toString())        //[object Object]


console.log(Object.prototype.toString) // toString() { [native code] }

//Deleting toString
var result = delete Object.prototype.toString
console.log(result)    //returns true 


console.log(Object.prototype.toString)

//undefined  toString no longer exists

//You can check it
function obj() {
    this.foo=1
    this.boo=2
}
obj1 = new obj()

console.log(obj1.toString())   //obj1.toString is not a function

Deleting predefined JavaScript methods like toString is not a good idea. It will crash the parts of the app (or third-party libraries) which use it.

Deleting Non Configurable Properties

Delete will not delete Non Configurable own Properties.

We can create a Non Configurable property using the defineProperty method of the object. The following example creates two properties canDelete & cannotDelete. In cannotDelete, we set configurable: false.

var obj = {};
Object.defineProperty(obj, 'canDelete', {
    value: "1",
    configurable: true
});
Object.defineProperty(obj, 'cannotDelete', {
    value: "2",
    configurable: false
});

result = delete obj.canDelete
console.log(result)     //true

result = delete obj.cannotDelete //cannotDelete cannot be deleted
console.log(result)     //false

console.log(obj)        //{cannotDelete: "2"}

Cannot delete functions & variable

You cannot delete regular variables, functions or function parameters using the delete Operator.

The variable declared with var is attached to the global object, but it is a not configurable property. Hence it cannot be deleted.

The let or const variables are not attached to any object. Hence they cannot be deleted.

 var sum = function(a, b) { return a + b; }
 delete sum               //deleting function

 console.log(typeof sum); //function
 console.log(sum(1,1))    //2   still works

Trying to delete a variable

 var num = 10 
 delete num         //deleting num

 console.log(num);  //10  still works

We cannot delete obj here as it is declared with let

let obj = {
    foo:'1',
    boo:'2'
}
console.log(obj)   //{ foo: '1', boo: '2' }

delete obj         // Does not delete obj
console.log(obj)   //{ foo: '1', boo: '2' }

obj is declared without let, var or const. Hence the delete operator will delete it.

obj = {
    foo:'1',
    boo:'2'
}
console.log(obj)   //{ foo: '1', boo: '2' }

delete obj         // deletes obj
console.log(obj)   //ReferenceError: obj is not defined

The code below deletes the property a from the obj. because a is own property of the obj

console.log("property deleted")
console.log("----------------")
obj = {a: []}
console.log(obj)        //{ a: [] }
delete obj.a
console.log(obj)        //{}       //property a deleted

In the following code, we pass the obj.a to the function deleteProperty1. But it will not delete the property. This is because function does not know which object o belongs to.

console.log("Property not deleted")
console.log("--------------------")
obj = {a: []}
console.log(obj)        //{ a: [] }
deleteProperty1(obj.a)    //We are passing property to the function
console.log(obj)        //{ a: [] }

function deleteProperty1(o) {
  delete o     //no error but o is not deleted.
}

To delete the property in a function, we need to pass both the object along with the property name as shown below

console.log("property deleted")
console.log("----------------")
obj = {a: []}
console.log(obj)        //{ a: [] }
deleteProperty2(obj,'a')
console.log(obj)  

function deleteProperty2(obj, prop) {
    if (obj[prop]) delete obj[prop];
}

The return value of delete

delete returns false if the property is an own property, but cannot be deleted. It returns true in all other cases. It will return true even if does not delete anything

Following are some examples.

var str="Test"
result = delete str.toString
console.log(result)           //true. But does not delete it
console.log(str.toString())   //it still works

In the following example, we try to delete a property that does not exist. Delete Operator returns true, although it does not delete anything


obj = {
    prop1: 'P1',
    prop2: 'P2',
}

console.log(obj)

var result = delete obj.prop3
console.log(result)    //true

console.log(obj)

Delete & Strict Mode

In strict mode deleting a non-configurable property throw a type error.

"use strict"

var obj = {};
Object.defineProperty(obj, 'cannotDelete', {
    value: "2",
    configurable: false
});

result = delete obj.cannotDelete //throws error becuase the Property non configurable

Deleting Array Elements

Delete Operator can also be used to delete an element in the array. JavaScript does not re arrange the array, but converts it into an sparse array. “sparse” array where the length is greater than the number of items or at least one item is missing at any of the index.

The code below deletes the element at index 2 (nums[2]) from the nums array. The Actual elements in array now becomes 3 but the length of the array does not become 3 but stays at 4. It is just that element at index 2 is removed and hence there is no value at that position. i.e. there is a hole in the array.

You can see that the when we loop through the array using the forEach it returns only 3 elements.

const nums =  Array("1","2","3","4")

console.log(nums.length)  //4

delete nums[2]

//only 3 elements in the array
nums.forEach(element => console.log(element));
//1
//2
//4

//But length still shows 4
console.log(nums.length)  //4  

But remember that the JavaScript returns nums[2] as undefined although the index 2 does not contain any value including undefined

The nums1 & nums2 arrays appears same below, but they are not. The nums1 array is a sparse array with no value at index 2, but the nums2 is not a sparse array because it has a value undefined at index 2.

const nums1 =  Array("1","2","3","4")
delete nums1[2]
console.log(nums1[2])  //Undefined  

const nums2 =  Array("1","2",undefined,"4")
console.log(nums2[2])  //Undefined  

Watch out for Undefined

Trying to access and property that does not exist returns undefined. Hence deleted Property returns undefined.

obj = {     foo:'1',     boo:'2' }

delete obj.foo    //deleting foo

console.log(obj.foo)  //undefined

Also, note that you can set a property to undefined, the Property still exists but has the value undefined. Hence merely checking for undefined does not tell you whether the property does exist or not.

obj2 = { foo: undefined}
console.log(obj2.foo)  //undefined

References

Delete

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top