sitifensys
sitifensys

Reputation: 2034

javascript property deletion

Just wondering about this one :

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

delete obj.someProperty

and

obj.someProperty=undefined

Upvotes: 4

Views: 103

Answers (4)

Quentin
Quentin

Reputation: 943569

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

This becomes significant if you loop over all the properties (for (props in obj) { }) or test for the existence of one (if ('someProperty' in obj) {})

Upvotes: 2

kassens
kassens

Reputation: 4475

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

Upvotes: 5

Dominic Barnes
Dominic Barnes

Reputation: 28429

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

Upvotes: 2

Eli
Eli

Reputation: 17825

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/

Upvotes: 3

Related Questions