re: Eradicating Memory Leaks In JavaScript VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Is assigning a variable to null the same as using the delete operator? Are there situations that favor one over the other?
 

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*

code of conduct - report abuse