How to remove a property from a JavaScript object?

To remove a property from a JavaScript object, you can use the delete operator or create a new object without the property. Here’s how:

1. Using the delete Operator

The delete operator removes a property directly from an object. This mutates the original object.

const person = { name: 'Alice', age: 30, city: 'Paris' };

// Remove the 'age' property
delete person.age;
// or: delete person['age'];

console.log(person); // { name: 'Alice', city: 'Paris' }

Notes:

  • delete only works on own properties (not inherited ones).
  • It returns true if successful, even if the property doesn’t exist.
  • Properties defined with Object.defineProperty and configurable: false cannot be deleted.

2. Creating a New Object Without the Property (Immutable Approach)

Use object destructuring or the spread operator to create a new object excluding the property. This leaves the original object unchanged.

const person = { name: 'Alice', age: 30, city: 'Paris' };

// Destructure to exclude 'age'
const { age, ...newPerson } = person;

console.log(newPerson); // { name: 'Alice', city: 'Paris' }
console.log(person);    // Original remains unchanged

Key Differences:

  • Mutability: delete modifies the original object, while destructuring creates a new one.
  • Use Case: Use delete for direct removal; use destructuring for immutability (e.g., React state updates).

Example Summary:

MethodCodeMutates Original?
delete Operatordelete obj.property;Yes
Destructuringconst { prop, ...rest } = obj;No

Choose the method based on whether you need to modify the original object or create a new one.

Leave a Reply

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