AppDividend
Latest Code Tutorials

Javascript Delete Operator Tutorial | Remove Property From Object

0

Javascript Delete Operator Tutorial | Remove Property From Object is today’s topic. The delete operator deletes a property from the object. If no more references to a same property are held, it is eventually released automatically. The delete operator deletes both the value of the property and the property itself. After the deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on the object properties. It does not affect variables or functions.

Javascript Delete Operator Tutorial

The syntax of Javascript Delete Operator is following.

delete object.property

// or

delete object['property']

Let’s see the following example.

// app.js

let appObj = {a: 21, b: 22, c: 23};
    
console.log(appObj.a);

delete appObj.a;

console.log(appObj);

The output is following.

 

Javascript Delete Operator Tutorial

One thing you need to keep in mind is that the delete operator should not be used on predefined JavaScript object properties. It can crash your application.

Now, if you try to delete the whole object, then it might not be possible for you. It can only remove the properties from the object and not the entire object.

// app.js

let appObj = {a: 21, b: 22, c: 23};
    
console.log(appObj);

delete appObj;

console.log(appObj);

The output is following.

 

How To Remove Property From Object

Unlike what common belief suggests, a delete operator in Javascript has nothing to do with directly freeing memory. Memory management is done indirectly by breaking references.

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

  1. If the property which you are trying to delete does not exist then, delete will not have any effect and will return true.
  2. If the 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.

Let’s see the following example of True or False.

// app.js

let appObj = {a: 21, b: 22, c: 23};
    
console.log(appObj);

console.log(delete appObj.d);

See the following example.

 

Javascript Delete Operator Tutorial | Remove Property From Object

You can see that if the object property does not exist and if you try to remove that property which does not exist then it will give us true in output.

Finally, Javascript Delete Operator Tutorial | Remove Property From Object is over.

Leave A Reply

Your email address will not be published.

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