Clearing Variables in JavaScript

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

What environment are you working in? Is this code you type directly into your browser console?

The short answer is that it’s not possible to manually destroy variables you create with a keyword (var). That’s up to the garbage collector, which is completely automated. I think the easiest solution for you is to wrap each code in an immediately invoked function expression. This is simply a function that runs immediately rather than being invoked later. It will create a context for each of your variables.

(function() { //create a new anonymous function, but put an opening paren in front of it
    function foo (str, a) {
        eval(str);
        console.log(a, b);
    }
    var b = 2
    foo("var b = 3", 1)
})() // Notice that the function gets closed off with another paren, and then there's
    // two more parentheses.  This is what invokes the function.

To generalize this, an IIFE (pronounced “iffy”) looks like this:

(function (parameters...) { /* code here */ })()

Sometimes you’ll see the invoking parentheses inside of the iffy:

(function (parameters...) { /* code here */ }())

This is a purely stylistic choice, but as with other stylistic choices, some programmers will literally murder you if you disagree with them.

1 Like