Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  15] [ 4]  / answers: 1 / hits: 31410  / 12 Years ago, tue, february 19, 2013, 12:00:00

Is there any substantial difference in doing either of these?



delete a.x;


vs



a.x = undefined;


where



a = {
x: 'boo'
};


could it be said that they are equivalent?



(I'm not taking into account stuff like V8 likes not using delete better)


More From » javascript

 Answers
14

They are not equivalent. The main difference is that setting


a.x = undefined

means that a.hasOwnProperty("x") will still return true, and therefore, it will still show up in a for in loop, and in Object.keys(). Whereas


delete a.x

means that a.hasOwnProperty("x") will return false


You can't tell if a property exists by testing


if (a.x === undefined)

If you are trying to determine if a property exists, you should always use


// If you want inherited properties
if ('x' in a)

// If you don't want inherited properties
if (a.hasOwnProperty('x'))

Following the prototype chain (mentioned by zzzzBov) Calling delete will allow it to go up the prototype chain, whereas setting the value to undefined will not look for the property in the chained prototypes




var obj = {
x: fromPrototype
};
var extended = Object.create(obj);
extended.x = overriding;
console.log(extended.x); // overriding
extended.x = undefined;
console.log(extended.x); // undefined
delete extended.x;
console.log(extended.x); // fromPrototype




Deleting Inherited Properties If the property you are trying to delete is inherited, delete will not affect it. That is, delete only deletes properties from the object itself, not inherited properties.




var obj = {x: fromPrototype};
var extended = Object.create(obj);
delete extended.x;
console.log(extended.x); // Still fromPrototype




Therefore, if you need to make sure an object's value will be undefined, delete will not work when the property is inherited, you will have to set (override) it to undefined in that case. Unless the place that is checking for it will use hasOwnProperty, but it likely wouldn't be safe to assume that everywhere that checks it will use hasOwnProperty


[#80121] Monday, February 18, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorw

Total Points: 484
Total Questions: 120
Total Answers: 107

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;