pointers - Deleting Objects in JavaScript

ID : 7214

viewed : 107

Tags : javascriptpointersobjectmemory-managementgarbage-collectionjavascript





Top 5 Answer for pointers - Deleting Objects in JavaScript

vote vote

99

The delete operator deletes only a reference, never an object itself. If it did delete the object itself, other remaining references would be dangling, like a C++ delete. (And accessing one of them would cause a crash. To make them all turn null would mean having extra work when deleting or extra memory for each object.)

Since Javascript is garbage collected, you don't need to delete objects themselves - they will be removed when there is no way to refer to them anymore.

It can be useful to delete references to an object if you are finished with them, because this gives the garbage collector more information about what is able to be reclaimed. If references remain to a large object, this can cause it to be unreclaimed - even if the rest of your program doesn't actually use that object.

vote vote

83

The delete command has no effect on regular variables, only properties. After the delete command the property doesn't have the value null, it doesn't exist at all.

If the property is an object reference, the delete command deletes the property but not the object. The garbage collector will take care of the object if it has no other references to it.

Example:

var x = new Object(); x.y = 42;  alert(x.y); // shows '42'  delete x; // no effect alert(x.y); // still shows '42'  delete x.y; // deletes the property alert(x.y); // shows 'undefined' 

(Tested in Firefox.)

vote vote

74

"variables declared implicitly" are properties of the global object, so delete works on them like it works on any property. Variables declared with var are indestructible.

vote vote

64

Coming from the Mozilla Documentation, "You can use the delete operator to delete variables declared implicitly but not those declared with the var statement. "

Here is the link: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Operators:Special_Operators:delete_Operator

vote vote

56

delete is not used for deleting an object in java Script.

delete used for removing an object key in your case

var obj = { helloText: "Hello World!" };  var foo = obj; delete obj; 

object is not deleted check obj still take same values delete usage:

delete obj.helloText 

and then check obj, foo, both are empty object.

Top 3 video Explaining pointers - Deleting Objects in JavaScript







Related QUESTION?