JavaScript

Deleting Objects in JavaScript

There are some situations where programmers need to delete the object, such as freeing up the memory when an object is no longer needed, updating an object, they may need to delete properties that are no longer relevant, restricting access to certain data, and so on.

This tutorial will describe the procedure to delete an object in JavaScript.

How to Delete Objects in JavaScript?

For deleting objects or the properties of an object, utilize the “delete” operator. It removes or deletes the properties from an object. It takes an object property as its operand and removes the property from the object. The delete operator outputs “true” if the property was successfully deleted and “false” if it couldn’t be deleted because it is a non-configurable property.

Syntax

The following syntax is used for the delete operator:

delete object.property

Example 1: Delete an Object in JavaScript

First of all, create an object:

var object = {

name: "Stephen",

age: 32,

designation: "HR"

};

Call the “delete” operator for deleting object:

delete object;

Print the object on the console. After deleting, it will display on the console because the delete operator removes only a reference to an item, never the object itself:

console.log(object);

Output

There is no need to delete objects, they will be deleted if there are no means of referring to them. You can delete the object’s properties that are not relevant or needed.

Example 2: Delete an Object’s Property in JavaScript

Here, we will delete the “age” from the object using the “delete” operator:

delete object.age;

Print the object with remaining properties on the console:

console.log(object);

It can be observed that the “age” property has been successfully deleted from an object:

That’s all about deleting objects in JavaScript.

Conclusion

For deleting objects or the properties of an object, utilize the “delete” operator. The delete operator only works on object properties, not objects themselves. It is used to remove a property from an object, not to delete the object itself. While deleting an object, the delete operator removes only a reference to an item, never the object itself. This tutorial described the procedure for deleting an object in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.