In Javascript what is more efficient, deleting an element or setting it to undefined explicitly

I didn't benchmark the performance of those operations (as I mentioned in a comment, just create a little benchmark on http://www.jsperf.com), but I'll lose some words on the difference.

You will always be good on deleteing properties, wheras setting them to undefined or null will let people and/or code hang, which check with the IN operator.

Like

if( 'bar' in Foo ) { }

will still return true if you set Foo.bar to undefined. It won't if you go with delete Foo.bar.


Be aware that deleting a property from an object will replace that property with one of the same name if one exists on the prototype chain.

Setting the property to null or undefined will simply mask it.


It'll make a negative performance difference in the long term as b is still considered a property after the latter assignment to undefined. For example:

var a = { b : 0 };

a.b = undefined;

a.hasOwnProperty("b");
>>> true

Same goes for the in keyword ("b" in a is true) so this will most likely hinder iteration when part of a larger object.

Tags:

Javascript