re: Eradicating Memory Leaks In JavaScript VIEW POST

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"}
-->{name: "Ford", model: "ecosport"}
delete car.model
-->{name: "Ford"}

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"}
-->{name: "Hyundai", model: "i20"}
car2.model = null;
-->{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