0
0
JavascriptHow-ToBeginner · 3 min read

How to Delete Property from Object in JavaScript: Simple Guide

To delete a property from an object in JavaScript, use the delete operator followed by the object and property name, like delete object.property. This removes the property from the object entirely.
📐

Syntax

The delete operator removes a property from an object. The syntax is:

  • delete object.property - deletes the property named property from object.
  • delete object['property'] - alternative syntax using bracket notation.

After deletion, the property no longer exists on the object.

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

Example

This example shows how to delete a property from an object and check the result.

javascript
const person = {
  name: 'Alice',
  age: 30,
  city: 'New York'
};

console.log('Before delete:', person);
delete person.age;
console.log('After delete:', person);
console.log('Age property exists?', 'age' in person);
Output
Before delete: { name: 'Alice', age: 30, city: 'New York' } After delete: { name: 'Alice', city: 'New York' } Age property exists? false
⚠️

Common Pitfalls

Some common mistakes when deleting properties:

  • Trying to delete a variable or a property declared with var, let, or const will not work.
  • Deleting properties from objects created with Object.freeze() or with non-configurable properties fails silently or throws errors in strict mode.
  • Using delete on array elements removes the element but leaves empty holes; use array methods instead.
javascript
const obj = { a: 1 };

// Wrong: deleting a variable
// let a = 10;
// delete a; // false, does not delete variable

// Right: deleting object property
console.log(delete obj.a); // true
console.log(obj); // {}
Output
true {}
📊

Quick Reference

Summary tips for deleting properties:

  • Use delete object.property to remove a property.
  • Check property existence with 'property' in object after deletion.
  • Do not use delete on variables or constants.
  • For arrays, prefer methods like splice() over delete.

Key Takeaways

Use the delete operator to remove a property from an object: delete object.property.
Deleted properties no longer exist on the object and return false when checked with 'in'.
Do not use delete on variables or constants; it only works on object properties.
Deleting array elements with delete leaves holes; use array methods like splice instead.
Properties that are non-configurable or frozen cannot be deleted.