No way to delete variables declared with var
The function of the operator delete
is to exclude properties of objects, not variables. Therefore 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 the object window
? Yes. And yet I can’t rule her out? Not. Why?
Environment Records
In Javascript, variables are considered properties of internal objects (Environment Records) that represent a certain scope and are not exposed to language - the fact that the global object is exposed as window
in browsers is a special case. Object properties, in turn, also have internal attributes defining certain aspects of their behaviour. One of them, called [[Configurable]] in the specification, defines whether the property can be excluded or not (among other restrictions).
In browsers, created global variables are always properties of window
. Those that are created with declaration (var
) receive value false
for the attribute [[Configurable]], and this prevents them from being deleted with delete window.varname
. Already implicit global, created without var
, follow a different path by the internal operations of the language, the end up receiving value true
to [[Configurable]], allowing them to be excluded with delete window.varname
. This can be considered a loophole in the language. It is good to note that it is advisable to avoid as far as possible the implicit global, who are also prohibited in the strict manner of language (the attempt to create them casts an exception).
Nonglobal variables
There is no way to exclude non-global variables for two reasons:
- The internal object containing them is not exposed by language
- Even if it were exposed, the variables are represented as properties with [[Configurable]]: false, and cannot be excluded with
delete
.
To exclude 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 release the corresponding memory if there is no reference left to the value that the variable contained (in the case of type values Object
or derivatives, there may be multiple variables pointing to the same object or parts of it).
Cannot delete variables declared with
var
in front.– Beterraba