DEV Community

Discussion on: Eradicating Memory Leaks In JavaScript

Collapse
 
somedood profile image
Basti Ortiz

Is assigning a variable to null the same as using the delete operator? Are there situations that favor one over the other?

Collapse
 
qm3ster profile image
Mihail Malo • Edited
{
const {log} = console
const obj = { a: 1, b: 2, c: 3}
obj.a = null
obj.b = undefined
delete obj.c
log(
  'a:', obj.hasOwnProperty('a'),
  'b:', obj.hasOwnProperty('b'),
  'c:', obj.hasOwnProperty('c')
)
for (const k in obj) log(k)
log(Object.entries(obj))
}

delete is definitely slower, but it removes the key (completely cleans the object of the assignment).
This can matter if you are using an object as a hashmap with a large key domain, for example if the keys are UUIDs.
Over prolonged/intensive use, this can result in a large object.

But no reason to mess around with disposing of the object and using a new one, or using delete - just don't use objects for such cases, use the new Map type instead. The .delete(key) method there is very fast.

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*