Deleting Object Properties in JavaScript

Rajan Tiwari
HackerNoon.com
2 min readJan 15, 2019

--

Recently I was working on a use case where I had an Object like below

Here, the API was designed in a way that we needed to send stone only when status was Time. Also for some reason I was given the input object in the above format.

I wanted to edit above object and just remove stone property entirely if status !== 'active'. So what I use to do was

One of my friend told me this seemed wrong as I was trying to delete the property by setting it to undefined . So I asked for the right way, but he couldn’t think of the other way which would do this in a better way. I used this way and moved ahead at that time.

Recently, I came across delete keyword in JavaScript which I had not known before. I also realized that when we set any property to undefined , we don’t actually delete the property.

Here’s an example to prove that. Now when we console.log the above object

So the property is alive is undefined but it still present in an object. So the right way of doing this:

So now the property is deleted from the object completely instead of having with value of undefined. This not only removes the property from object but also saves memory by deleting its reference.

But don’t worry about Dr Strange he is hiding somewhere in the past, so might as well come to save Avengers in End Game.

--

--