I tried it, but delete
doesn't work.
var x = {"y":42,"z":{"a":1,"b":[1,2,3]}};
alert(x.y);
delete x;
alert(x.y); // still shows '42'
How to delete the full object crossbrowser?
Edit:
x = null
also doesn't work
I tried it, but delete
doesn't work.
var x = {"y":42,"z":{"a":1,"b":[1,2,3]}};
alert(x.y);
delete x;
alert(x.y); // still shows '42'
How to delete the full object crossbrowser?
Edit:
x = null
also doesn't work
- Would be a good idea to mention in which browsers it doesn't work... – ThiefMaster Commented Apr 3, 2012 at 21:12
- 1 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 it – Matt Commented Apr 3, 2012 at 21:23
6 Answers
Reset to default 6You 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
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;
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();
aa
>> delete f1;
false
>> f1();
aa
But if you declare a global function as a window attribute, you can delete it:
>> f1 = f1() {console.log("aa");}
>> delete window.f1;
true
The same is for variables:
>> a = "x";
>> console.log(a);
x
>> delete window.a;
true
>> console.log(a);
ReferenceError: a is not defined
But:
>> var a = "x";
>> console.log(a);
x
>> delete a;
false
>> console.log(a);
x
You can't delete an object from the global namespace in Javascript.
You can delete
objects within x
, but not x
itself.
Try x = null;
or x = undefined;
.
You probably set object with const instead of var