How do you safely delete or remove a property from a JavaScript object?
Removing a property from a JavaScript object safely without mutating the original object using object rest destructuring (const { keyToRemove, …cleanObj } = obj) gives you a clean new object without that key. When you want to remove a property directly on an existing object, delete obj.keyToRemove removes the property from the object itself.
Safe Ways to Remove an Object Property
1- Non-mutating copy: Destructuring pulls out the unwanted key and places the remaining properties into a new object.
2- Direct deletion: delete obj.key removes the property directly from the existing object and returns true.
3- Avoid hot-loop deletion: Do not use delete inside performance-critical loops on large objects.
Example: Removing a Property from an Object
JavaScript
const user = { id: 101, name: "Nadia", tempToken: "xyz789" };
// Creates a new object without `tempToken`
const { tempToken, ...safeUser } = user;
console.log(safeUser); // { id: 101, name: "Nadia" }
console.log(user.tempToken); // "xyz789"
// Removes `tempToken` directly from `user`
delete user.tempToken;
console.log(user); // { id: 101, name: "Nadia" }
You must log in or register to comment.
