Deleting a variable in JavaScriptQuestion: Can I delete a JavaScript variable? Answer: Not always it depends. var x; ) at the time of first use.
x first appeared in the script without a declaration, then you can use the
delete operator delete 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 var keyword
at the time of first use, then delete will 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.