When should I use delete vs setting elements to null in JavaScript? [duplicate]

There is no way to force garbage collection in JavaScript, and you don’t really need to. x.y = null; and delete x.y; both eliminate x‘s reference to the former value of y. The value will be garbage collected when necessary.

If you null out a property, it is still considered ‘set’ on the object and will be enumerated. The only time I can think of where you would prefer delete is if you were going to enumerate over the properties of x.

Consider the following:

var foo = { 'a': 1, 'b': 2, 'c': 3 };

console.log('Deleted a.');
delete foo.a
for (var key in foo)
  console.log(key + ': ' + foo[key]);

console.log('Nulled out b.');
foo['b'] = null;
for (var key in foo)
  console.log(key + ': ' + foo[key]);

This code will produce the following output:

Deleted a.
b: 2
c: 3
Nulled out b.
b: null
c: 3

Leave a Comment