There is no way to delete variables declared with
The function of the
delete operator is to exclude properties of objects, not variables. So in principle it would not serve to exclude variables.
But if I declare
var x = 10 and I can access it as
window.x , then
x is not a property of object
window ? Yes. And still not Can I delete it? No Why?
window in browsers is a special case . Object properties, in turn, also have internal attributes that define certain aspects of their behavior. One of them, called [[Configurable]] in the specification, defines whether or not the property can be deleted (among other constraints).)
In browsers, global variables created are always
window properties. Those that are created with declaration (
var ) are given
false value for the [[Configurable]] attribute, and this prevents them from being deleted with
delete window.varname . Implicit global, created without
var , follow a different path by the internal operations of the language, they end up receiving
true value for [[Configurable]], allowing them to be excluded with
delete window.varname . This can be considered a breach in language. It's good to note that we recommend avoiding implicit globals . , which are also prohibited by strict mode of the language (the attempt to create them throws an exception).
There is no way to exclude non-global variables, for two reasons:
- The internal object that contains them is not exposed by the language
- Even if it were exposed, variables are represented as properties with [[Configurable]]: false, and can not be excluded with
Why delete variables?
A good reason to delete variables would be to free up memory. If this is your goal, simply set the value of the variable to
null , and the garbage collector will free the corresponding memory if there is no reference left over to the value that the variable contained (in the case of values of type
Object or derivatives, there can be multiple variables pointing to the same object or parts of it).