Deleting Object Properties in JavaScript
Recently I was working on a use case where I had an Object like below
let obj1 = {
name: "Dr Strange",
stone: "Time",
status: "alive"
}
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
//incorrect way
if(obj1.status !== 'active')
obj1.stone= undefined;
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
console.log(obj1) // {name: "Vision", stone: "Time", alive: undefined}
So the property is alive
is undefined but it still present in an object. So the right way of doing this:
let obj1 = {
name: "Dr Strange",
stone: "Time",
alive: true
}
delete obj1.alive;
obj1 // {name: "Vision", stone: "Soul"}
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.