0

Background

  • I would like to completely wipe out the variable from JavaScript interpreter.
  • delete keyword does not work.

    > let foo = { };
    undefined
    > delete foo
    true
    > foo
    {}
    
  • Setting variable to undefined does not work.

    > let foo = { };
    undefined    
    > foo = undefined
    undefined
    > foo
    undefined
    > let foo = { };
    SyntaxError: Identifier 'foo' has already been declared
    

Question

  1. Is it possible to completely wipe out variable from JavaScript interpreter?
  2. If yes, how to do that?
MaciejLisCK
  • 3,706
  • 5
  • 32
  • 39
  • 1
    Just assign it to `null`. `delete` is for deleting properties from object. – Fuross Sep 21 '17 at 15:47
  • Nope it does not work, if I assign to null `> foo = null` and I want to redeclare variable `> let foo = { };`, I receive following error: `SyntaxError: Identifier 'foo' has already been declared`, so it is not completely wiped out. – MaciejLisCK Sep 21 '17 at 15:50
  • 1
    @Fuross: Assigning `null` to a variable doesn't remove the variable, it just puts the value `null` in it. – T.J. Crowder Sep 21 '17 at 15:53

1 Answers1

1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875