Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 460
Marc Avatar asked Apr 03 '18 14:04

Marc


2 Answers

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

like image 144
Paul Avatar answered Nov 14 '22 22:11

Paul


This is just the way it's specified, if you want the worse behaviour you can use var.

Redeclaring the same variable within the same function or block scope raises a SyntaxError.

if (x) {
  let foo;
  let foo; // SyntaxError thrown.
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

like image 27
Dominic Avatar answered Nov 14 '22 23:11

Dominic