Is it possible to completely wipe out variable from JavaScript interpreter?
Yes and no, it depends on the variable and how it was created. You cannot remove a global var
or let
variable (or global const
). For the "yes" cases, see below.
If yes, how to do that?
It depends on where the variable is defined:
1) If it's a global variable, don't declare it with let
or var
; instead, assign to a property of the global object (this
at global scope; also accessible via the global window
on browsers or global
on NodeJS). When you want to remove it, use delete
.
window.foo = "bar";
console.log("foo" in window); // true
console.log(foo); // "bar"
delete window.foo;
console.log("foo" in window); // false
console.log(foo); // ReferenceError: foo is not defined
I should note that in loose mode, you can also do that by relying on The Horror of Implicit Globals (that's a post on my anemic little blog) by just assigning to an undeclared identifier:
foo = "bar";
console.log("foo" in window); // true
console.log(foo); // "bar"
delete foo;
console.log("foo" in window); // false
console.log(foo); // ReferenceError: foo is not defined
But...use strict mode, for exactly this reason, so typos don't make it very far. :-)
2) If it's in a function, ensure that the function returns without creating any closures. All of its local variables are then completely removed.