How to delete full object with javascript?

Go To


I tried it, but delete doesn't work.

var x = {"y":42,"z":{"a":1,"b":[1,2,3]}};

delete x;

alert(x.y); // still shows '42'

How to delete the full object crossbrowser?

Edit: x = null also doesn't work

2012-04-03 21:10
by Danny Fox
Would be a good idea to mention in which browsers it doesn't work.. - ThiefMaster 2012-04-03 21:12
what do you mean x = null doesn't work? If you are referring to accessing it, x.y will most certainly fail after assigning null to x. If you are referring to reclaiming memory, then the object that was assigned to x will be cleaned up by garbage collection, if there are no other references to i - Matt 2012-04-03 21:23


You can only use the delete operator to delete variables declared implicitly, but not those declared with var. You can set x = null or x = undefined

2012-04-03 21:16
by Luca


You don't need to delete objects in JavaScript. The object will be garbage collected after all references to it are removed. To remove the reference, use:

x = null;
2012-04-03 21:13
by Kendall Frey


You cannot delete a variable or a function. Only a property of an object. You can simply assign:

x = null;

if you want to clear its value.

UPDATE: clarification regarding functions:

>> function f1() {console.log("aa");}
>> f1();
>> delete f1;
>> f1();

But if you declare a global function as a window attribute, you can delete it:

>> f1 = f1() {console.log("aa");}
>> delete window.f1;

The same is for variables:

>> a = "x";
>> console.log(a);
>> delete window.a;
>> console.log(a);
ReferenceError: a is not defined


>> var a = "x";
>> console.log(a);
>> delete a;
>> console.log(a);
2012-04-03 21:12
by Eugene Retunsky
Not true, regarding functions. See my comment to @Spudley below - Matt 2012-04-03 21:20
You can delete a function if it's a member of an object. But you cannot remove a globally defined function - Eugene Retunsky 2012-04-03 21:40
What do you mean by globally defined? by default, a global variable exists under the 'window' scope chain. Try it form the Chrome console func1 = function(){}, then delete window.func1. It will delete successfull - Matt 2012-04-03 22:02
I updated my answer to show what I meant under "you cannot delete a function" - Eugene Retunsky 2012-04-03 22:10
@Matt running this kind of JS code on a developer console is fraught with danger because the code is eval-ed, and that may lead you to incorrect conclusions. See to understand why - JamieJag 2013-01-04 10:58


You can't delete an object from the global namespace in Javascript.

You can delete objects within x, but not x itself.

2012-04-03 21:13
by Spudley
From Chrome console, I can do window.func1 = function(){}, and then delete window.func1. I can also do func2 = function(){} followed by a delete. However, I can not do function func3(){}. Calling delete on that returns false, and the function remains - Matt 2012-04-03 21:16


Try x = null; or x = undefined;.

2012-04-03 21:14
by jches