Variables declared with var
are added as properties on the global window
object and cannot be deleted with the delete
operator.
From MDN - var:
In the global context, a variable declared using var is added as a
non-configurable property of the global object. This means its
property descriptor cannot be changed and it cannot be deleted using
delete.
Reason for this is also explained:
The property created on the global object for global variables, is set
to be non-configurable because the identifier is to be treated as a
variable, rather than a straightforward property of the global object.
JavaScript has automatic memory management, and it would make no sense
to be able to use the delete operator on a global variable.
Also note that trying to delete a property set on of global window
object for variables declared with var
fails silently in non-strict mode and throws a TypeError
in strict-mode.
Also note that you can delete a property from the window
object if is set explicitly.
var a = 1; // can't be deleted
window.b = 2; // can be deleted
delete window.a;
delete window.b;
console.log(window.a);
console.log(window.b);