Optional Chaining with Delete
You'll learn how to safely delete properties from objects that might not exist using the delete operator combined with optional chaining.
The Core Idea
You've learned that optional chaining (?.) lets you safely access nested properties without throwing errors when intermediate values are null or undefined. This same safety applies when deleting properties: delete obj?.prop will only attempt to delete the property if obj itself isn't nullish.
How It Works
The delete operator normally throws an error if you try to delete a property from something that doesn't exist. With optional chaining, the delete operation simply short-circuits and returns true if the object is null or undefined:
const user = { profile: { avatar: 'pic.jpg' } };
// Safe deletion - removes avatar if profile exists
delete user.profile?.avatar;
console.log(user.profile); // { } (empty object)
// Without optional chaining, this would throw:
const noUser = null;
delete noUser?.profile; // Returns true, no error
Deeper Nesting
This combines beautifully with nested optional chaining:
const data = { settings: { ui: { theme: 'dark' } } };
// Only deletes if the entire chain exists
delete data.settings?.ui?.theme;
console.log(data.settings.ui); // { } (theme removed)
// If any part is nullish, it short-circuits safely
const incomplete = { settings: null };
delete incomplete.settings?.ui?.theme; // Returns true, no error
Why This Matters
Before optional chaining, you'd need to check existence at every level before deleting, creating verbose guard clauses. Now you can express intent cleanly in one line, letting JavaScript handle the safety checks.
Key Takeaway: Use delete obj?.prop to safely remove properties only when the parent object exists, avoiding errors when dealing with potentially nullish values.