How To Delete Property From Object Javascript

JavaScript objects are essential data structures in modern web development. It’s common to add, modify, and delete properties from objects as needed. In this blog post, we’ll show you how to delete a property from an object in JavaScript using the delete operator.

The ‘delete’ Operator

The delete operator is a unary operator that removes a property from an object. Its syntax is simple:

delete object.property;
delete object['property'];

Let’s illustrate this with an example. Consider the following object:

const person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30
};

To delete the age property from the person object, simply use the delete operator like this:

delete person.age;

Or, if you prefer the bracket notation:

delete person['age'];

Now, when you try to access the age property of the person object, it will return undefined since the property has been deleted:

console.log(person.age); // Output: undefined

Deleting a Property with a Variable Name

If you need to delete a property whose name is stored in a variable, you can use the bracket notation with the delete operator. Here’s an example:

const person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30
};

const propName = 'age';

delete person[propName];

This code will also delete the age property from the person object.

Conclusion

Deleting a property from an object in JavaScript is straightforward using the delete operator. Just remember that the delete operator only removes the property and its value from the object; it does not affect any other reference to that value.