Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Say I have an Associative Array Foo, with key bar and value xyz.

 console.log(Foo['bar']);

 >> xyz

 delete Foo['bar'];
 console.log Foo['bar'];

 >> undefined

 Foo['bar'] = 'xyz';
 console.log(Foo['bar']);

 >> xyz

 Foo['bar'] = undefined;
 console.log (Foo['bar']);

 >> undefined

My question is, which of the two is more efficient, do they differ in any way? Is there a scenario when I should use one over the other?

Thanks!

Results:

Thank you to everyone for helping out and showing me jsperf. Setting it to undefined appears to be (relatively) significantly faster then delete, although all the caveats pointed out below are also very interesting (in fact, I will probably be using delete a lot going forward to avoid future errors out of leftfield).

like image 613
Abraham P Avatar asked Dec 20 '12 23:12

Abraham P


People also ask

Why we should not use Delete in JavaScript?

it's only effective on an object's properties, it has no effect on variable or function names. The delete operator shouldn't be used on predefined JavaScript object properties like window , Math , and Date objects. It can crash your application.

Is delete slow JavaScript?

Since delete ary[0] does not change the length of the array, you'd think that it wouldn't be much work for the engine to accomplish, but (in my testing) it is indeed a slow operation.

What is the use of Delete in JavaScript?

The delete operator removes a given property from an object. On successful deletion, it will return true , else false will be returned.

How do you clear an object in JavaScript?

Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property.


2 Answers

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.

like image 112
jAndy Avatar answered Oct 11 '22 15:10

jAndy


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.

like image 23
Aesthete Avatar answered Oct 11 '22 15:10

Aesthete