admin管理员组

文章数量:1317910

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.

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.

Share Improve this question asked Apr 3, 2018 at 14:31 MarcMarc 11.6k2 gold badges39 silver badges48 bronze badges 2
  • 1 The answer is "no", but there are workarounds for your specific problem. – Pointy Commented Apr 3, 2018 at 14:36
  • One workaround would be to check if it is undefined, and on only in that case define it - otherwise just assign to it – lucidbrot Commented Feb 4, 2020 at 13:38
Add a ment  | 

3 Answers 3

Reset to default 8

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

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/en-US/docs/Web/JavaScript/Reference/Statements/let

Let say somewhere in the code, a variable has been defined as let a = 2 and you want to redefine it, just use a = 3 if the original variable a is in scope. Deleting a from window won't work because definitions of a using let won't attach it to the window object.

本文标签: varJavascript How to Undefine (or Redefine) a quotletquotdefined variableStack Overflow