Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript property deletion

Tags:

javascript

Just wondering about this one :

Whats the difference, or is there a difference at all, between :

delete obj.someProperty

and

obj.someProperty=undefined
like image 644
sitifensys Avatar asked Dec 16 '22 13:12

sitifensys


2 Answers

The second version sets the property to the existing value undefined while 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's there with the value of undefined
delete obj.prop;
'prop' in obj; // false
like image 145
kassens Avatar answered Dec 30 '22 16:12

kassens


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

Here is some great (albeit advanced) information on deleting in JavaScript:

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

like image 33
Eli Avatar answered Dec 30 '22 16:12

Eli