Remove a property from a JavaScript object

In this article we will discuss about What is the best way to remove the property to end up with new myObject as follows. It ‘s quite simple, let’s take a look at this sample code:

Delete is the only true way to remove object’s properties without any leftovers, but it works ~ 100 times slower, compared to its “alternative”, setting object[key] = undefined.

This alternative is not the correct answer to this question! But, if you use it with care, you can dramatically speed up some algorithms. If you are using delete in loops and you have problems with performance, read the verbose explanation.

When should one use delete and when set value to undefined ?
An object may be seen as a set of key-value pairs. What I call a ‘value’ is a primitive or a reference to other object, connected to that ‘key’.

Use delete, when you are passing the result object to the code on which you don’t have control (or when you are not sure about your team or yourself).

It deletes the key from the hashmap.

Use setting to undefined, when you care about performance. It can give a serious boost to your code.

The key remains on its place in the hashmap, only the value is replaced with undefined. Understand, that for..in loop will still iterate over that key.

Using this method, not all ways of determining property existence will work as expected.

However, this code:

will behave equivalently for both methods.

Reference: http://perfectionkills.com/understanding-delete/

Leave a Reply

Your email address will not be published. Required fields are marked *

*