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.
- 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
3 Answers
Reset to default 8Type 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
版权声明:本文标题:var - Javascript: How to Undefine (or Redefine) a "let"-defined variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742029037a2416097.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论