DEV Community

Discussion on: Eradicating Memory Leaks In JavaScript

Collapse
 
nikhiltyagi04 profile image
nikhiltyagi04 • Edited

delete operator will eliminate both the key and the value while assigning something to null will only eliminate the value. This example should make it clear. Open up console in your chrome dev tools and try out the code below.

var car = {"name":"Ford", "model":"ecosport"}
car.model
-->"ecosport"
console.log(car)
-->{name: "Ford", model: "ecosport"}
delete car.model
-->true
console.log(car)
-->{name: "Ford"}
car.model
-->undefined

As you can see delete operator has eliminated both property and the value from the object. Both "model" property and its value "ecosport" have been cleared. car.model will now return undefined and there is no longer model property in the car object.

Now if you assign the property to null instead of delete operator, the value will be assigned to null but the property will not be cleared from the object. For example:

var car2 = {"name":"Hyundai", "model":"i20"}
car2.model
-->"i20"
console.log(car2)
-->{name: "Hyundai", model: "i20"}
car2.model = null;
-->null
console.log(car2)
-->{name: "Hyundai", model: null}

You can see that model property is still present in the car2 object and car2.model will return null, not undefined.

It is always better to delete unwanted properties. Assigning it to null won't clear the property and it will bother you if you are using any such object in loops or some other methods. Also note that delete can be used to remove a property from an object and also global variables*