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).
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.
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.
The delete operator removes a given property from an object. On successful deletion, it will return true , else false will be returned.
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.
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 delete
ing 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With