Deleting a property from an object in JavaScript can be done in several ways, each with its own features and use cases. Main methods: [delete] operator, destructuring with rest parameters, and functional approaches creating new objects.
Main deletion methods:
Deleting properties from objects is a common operation in JavaScript, requiring understanding of different approaches and their features. Method choice depends on data mutability requirements and usage context.
Directly removes property from object:
const obj = { a: 1, b: 2, c: 3 };
delete obj.b; // obj = { a: 1, c: 3 }Creates new object without specified property:
const { b, ...rest } = obj; // rest doesn't contain property b// Mutating approach
delete obj.property;
// Non-mutating approach
const { property, ...newObj } = obj;const obj = { a: 1, b: 2 };
// Property deletion
delete obj.b;
console.log('b' in obj); // false
// Assigning undefined
obj.b = undefined;
console.log('b' in obj); // trueconst user = {
name: 'John',
age: 30,
password: '12345',
email: 'john@example.com'
};
// Removing one property
delete user.password;
// Removing multiple properties via destructuring
const { password, age, ...safeUser } = user;function removeProperty(obj, key) {
if (key in obj) {
delete obj[key];
return true;
}
return false;
}// ❌ No existence check
delete obj.nonExistent; // Returns true, but does nothing
// ✅ Check before deletion
if ('property' in obj) {
delete obj.property;
}// ❌ Deleting inherited properties
const obj = Object.create({ inherited: 'value' });
delete obj.inherited; // Won't delete property from prototype
// ✅ Check property source
if (obj.hasOwnProperty('inherited')) {
delete obj.inherited;
}All property deletion methods are supported by all modern browsers:
The correct deletion method choice depends on data mutability requirements, performance, and supported browsers.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪