Deleting a variable in JavaScript

JavaScript FAQ | Basic Syntax & General Questions  

Question: Can I delete a JavaScript variable?

Answer: Not always – it depends.

  • You cannot delete a variable if you declared it (with
var x;
) at the time of first use.
  • However, if your variable
x
first appeared in the script without a declaration, then you can use the
delete
operator (
delete x;
) and your variable will be deleted, very similar to deleting an element of an array or deleting a property of an object.

A longer answer: If you declared your variable

x
with the
var
keyword at the time of first use, then
 delete x 
will not have any effect:
x
will still be available and hold the same value as before. As a partial workaround, you can set your variable to
null
or to
undefined
; however, this is not equivalent to deleting the variable, as shown in the example below.
// 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)); // true
Surprisingly, 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 © 1996-2018, JavascriptFAQ.net.