Search code examples
javascriptvarlet

Javascript: How to Undefine (or Redefine) a "let"-defined variable


Is it possible to undefine a let-defined variable so I can then redefine it? With var, I can just redefine the same variable over and over again. With let, a second attempt to define the variable is met with an error.

(You might wonder why I want to do this, and the reason is because I often run and re-run little one-line and multi-line scripts from my browser console, copied and pasted from elsewhere or as a bookmarklet. If those little scripts define a variable using let, then a re-run of the script fails. I could just continue to use var in these cases, but I'm trying to embrace the new order. And regardless of whether you think my use case is valid, the question stands.)

I've tried to delete it from the window object and some other hacks, but to no avail.


Solution

  • Type a { before the script and a } after it so that you are running the script inside a new block scope.