| Deleting a variable in JavaScript
 Question: Can I delete a JavaScript variable? Answer: Not always  it depends. var x;) at the time of first use.xfirst appeared in the script without a declaration, then you can use thedeleteoperatordelete x;)A longer answer: If you declared your variable  // x does not exist yet document.write(x); // Error: x is not defined document.write(typeof x); // undefined document.write(window.hasOwnProperty(x)); // Error: x is not defined // declare x with the var keyword var x = 1; // 1 document.write(typeof x); // number document.write(window.hasOwnProperty(x)); // false // delete x does not work. delete x; document.write(x); // 1 document.write(typeof x); // number document.write(window.hasOwnProperty(x)); // false x=null; // null document.write(typeof x); // object document.write(window.hasOwnProperty(x)); // false x=undefined; // undefined document.write(typeof x); // undefined document.write(window.hasOwnProperty(x)); // trueSurprisingly, if you have not declared your variable with the varkeyword
at the time of first use, thendeletewill work:// y is first used without var declaration
y = 1;                                    // 1
document.write(typeof y);                 // number
document.write(window.hasOwnProperty(y)); // false
// now y is belatedly declared using var 
var y;                                    // 1
document.write(typeof y);                 // number
document.write(window.hasOwnProperty(y)); // false
y=null;                                   // null
document.write(typeof y);                 // object
document.write(window.hasOwnProperty(y)); // false
                                         
y=undefined;                              // undefined
document.write(typeof y);                 // undefined
document.write(window.hasOwnProperty(y)); // true
// delete y WORKS!
delete y;                                    
document.write(y);                        // Error: y is not defined
document.write(typeof y);                 // undefined
document.write(window.hasOwnProperty(y)); // Error: y is not defined
See also: | 
 | 
Copyright © 1999-2011, JavaScripter.net.