Removing javascript property

Just wondering about this:

What is the difference or even the difference between:

delete obj.someProperty 

and

 obj.someProperty=undefined 
+4
source share
4 answers

The second version sets the property to the existing undefined value, and the first removes the key from the object. The difference can be seen when iterating over the object or using the in keyword.

 var obj = {prop: 1}; 'prop' in obj; // true obj.prop = undefined; 'prop' in obj; // true, it there with the value of undefined delete obj.prop; 'prop' in obj; // false 
+5
source

The difference will be realized when iterating over the object. When deleting a property, it will not be included in the loop, while changing it will include only the value undefined. The length of the object or the number of iterations will be different.

Here are some excellent (albeit advanced) JavaScript removal information:

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

+3
source

Using delete will actually remove the key from the object. If you set the value to undefined , they still exist, but this is the only thing that has changed.

+2
source

The former will actually delete the property, the latter will leave it, but set it to undefined .

This becomes significant if you for (props in obj) { } over all properties ( for (props in obj) { } ) or check for one ( if ('someProperty' in obj) {} )

+2
source

All Articles