I can\'t find any information on this issue; why doesn\'t the following code work in IE?
window.x = 45;
delete window.x;
// or delete window[\'x\'];
Gasper made a comment with the solution he finished on, but I think its worth calling out as an actual answer:
try
{
delete window.x;
}
catch(e)
{
window["x"] = undefined;
}
Interesting issue, I was just banging my head against it tonight. The exception is thrown on IE but not Firefox. I would suspect this workaround leaks memory, so use sparingly.
It was asked, why not just assign undefined? It matters if you want to enumerate the keys later (though if you're relying on the workaround, the key enumeration still won't do what you want...). But anyhow, to highlight the difference between delete and simply assigning undefined (http://jsfiddle.net/fschwiet/T4akL/):
var deleted = {
a: 1
};
var cleared = {
a: 1
};
delete deleted["a"];
cleared["a"] = undefined;
for(var key in deleted) {
console.log("deleted has key", key);
}
for(var key in cleared) {
console.log("cleared has key", key);
}
console.log("deleted has a?", deleted.hasOwnProperty('a'));
console.log("cleared has a?", cleared.hasOwnProperty('a'));
produces output:
cleared has key a
deleted has a? false
cleared has a? true