[javascript] Deleting Objects in JavaScript

I'm a bit confused with JavaScript's delete operator. Take the following piece of code:

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

var foo = obj;

delete obj;

After this piece of code has been executed, obj is null, but foo still refers to an object exactly like obj. I'm guessing this object is the same object that foo pointed to.

This confuses me, because I expected that writing delete obj deleted the object that obj was pointing to in memory—not just the variable obj.

Is this because JavaScript's Garbage Collector is working on a retain/release basis, so that if I didn't have any other variables pointing to the object, it would be removed from memory?

(By the way, my testing was done in Safari 4.)

The answer is


Just found a jsperf you may consider interesting in light of this matter. (it could be handy to keep it around to complete the picture)

It compares delete, setting null and setting undefined.

But keep in mind that it tests the case when you delete/set property many times.


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


I stumbled across this article in my search for this same answer. What I ended up doing is just popping out obj.pop() all the stored values/objects in my object so I could reuse the object. Not sure if this is bad practice or not. This technique came in handy for me testing my code in Chrome Dev tools or FireFox Web Console.


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.)


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.


This work for me, although its not a good practice. It simply delete all the the associated element with which the object belong.

 for (element in homeService) {
          delete homeService[element];
  }

"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.


Aside from the GC questions, for performance one should consider the optimizations that the browser may be doing in the background ->

http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/

It appears it may be better to null the reference than to delete it as that may change the behind-the-scenes 'class' Chrome uses.


Setting a variable to null makes sure to break any references to objects in all browsers including circular references being made between the DOM elements and Javascript scopes. By using delete command we are marking objects to be cleared on the next run of the Garbage collection, but if there are multiple variables referencing the same object, deleting a single variable WILL NOT free the object, it will just remove the linkage between that variable and the object. And on the next run of the Garbage collection, only the variable will be cleaned.


IE 5 through 8 has a bug where using delete on properties of a host object (Window, Global, DOM etc) throws TypeError "object does not support this action".

var el=document.getElementById("anElementId");
el.foo = {bar:"baz"};
try{
    delete el.foo;
}catch(){
    //alert("Curses, drats and double double damn!");
    el.foo=undefined; // a work around
}

Later if you need to check where the property has a meaning full value use el.foo !== undefined because "foo" in el will always return true in IE.

If you really need the property to really disappear...

function hostProxy(host){
    if(host===null || host===undefined) return host;
    if(!"_hostProxy" in host){
       host._hostproxy={_host:host,prototype:host};
    }
    return host._hostproxy;
}
var el=hostProxy(document.getElementById("anElementId"));
el.foo = {bar:"baz"};

delete el.foo; // removing property if a non-host object

if your need to use the host object with host api...

el.parent.removeChild(el._host);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to pointers

Method Call Chaining; returning a pointer vs a reference? lvalue required as left operand of assignment error when using C++ Error: stray '\240' in program Reference to non-static member function must be called How to convert const char* to char* in C? Why should I use a pointer rather than the object itself? Function stoi not declared C pointers and arrays: [Warning] assignment makes pointer from integer without a cast Constant pointer vs Pointer to constant How to get the real and total length of char * (char array)?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to memory-management

When to create variables (memory management) How to check if pytorch is using the GPU? How to delete multiple pandas (python) dataframes from memory to save RAM? Is there a way to delete created variables, functions, etc from the memory of the interpreter? C++ error : terminate called after throwing an instance of 'std::bad_alloc' How to delete object? Android Studio - How to increase Allocated Heap Size Implementing IDisposable correctly Calculating Page Table Size Pointer-to-pointer dynamic two-dimensional array

Examples related to garbage-collection

When to create variables (memory management) Difference between Xms and Xmx and XX:MaxPermSize Java GC (Allocation Failure) How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors? Implementing IDisposable correctly How to check heap usage of a running JVM from the command line? how to destroy an object in java? How to force deletion of a python object? How can I read a large text file line by line using Java? GC overhead limit exceeded