This page looks best with JavaScript enabled

Deleting Object Properties The Right Way in Javascript

 ·   ·  ☕ 1 min read

Do not set properties to null or empty, always use delete.

Consider -

1
2
3
const earth = { name: "earth", position: 3, aweIndex: 42 };
console.log(earth);
// { name: 'earth', position: 3, aweIndex: 42 }

If you set any property to null -

1
2
3
earth["aweIndex"] = undefined;
console.log(earth);
// { name: 'earth', position: 3, aweIndex: undefined }

You can expect similar results if you set the prop to null.

If you really want to delete the object, do a delete prop.

1
2
3
delete earth["aweIndex"];
console.log(earth);
// { name: 'earth', position: 3 }

And before you ask - yes, this is covered when we were discussing (almost) everything about object and props in Javascript.

But, this deserves 30 lines of its own due to the sheer number of ‘doubts’ about how to delete a prop. Sheesh.. Haven’t y’ll heard of Google? No..? - you always have this post to link back to. You are welcome.

For all that there is - I still think an Object.removeProperty() would have done just fine instead of the confusing delete. We have been brought up to not prefix delete against commands without thinking five times - that is a lot of effort.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things