Skip to content

How to quickly clear a JavaScript Object?

With a JavaScript Array, I can reset it to an empty state with a single assignment:

array.length = 0;

This makes the Array “appear” empty and ready to reuse, and as far as I understand is a single “operation” – that is, constant time.

Is there a similar way to clear a JS Object? I know I can iterate its fields deleting them:

for (var prop in obj) { if (obj.hasOwnProperty(prop)) { delete obj[prop]; } }

but this has linear complexity.

I can also just throw the object away and create a new one:

obj = {};

But “promiscuous” creation of new objects leads to problems with Garbage Collection on IE6. (As described here)


The short answer to your question, I think, is no (you can just create a new object).

  1. In this example, I believe setting the length to 0 still leaves all of the elements for garbage collection.

  2. You could add this to Object.prototype if it’s something you’d frequently use. Yes it’s linear in complexity, but anything that doesn’t do garbage collection later will be.

  3. This is the best solution. I know it’s not related to your question – but for how long do we need to continue supporting IE6? There are many campaigns to discontinue the usage of it.

Feel free to correct me if there’s anything incorrect above.