admin管理员组文章数量:1334342
I was playing around in Chrome devtools and tried the following code:
let = 1;
let x = 2;
console.log(let); // 1
console.log(x); // 2
I was playing around in Chrome devtools and tried the following code:
let = 1;
let x = 2;
console.log(let); // 1
console.log(x); // 2
The code above won't work if I replace "let" with "var".
I'm assuming that let = 1
is the same as var let = 1
. If so, shouldn't let x = 2
be translated to 1 x = 2
and therefore be an error?
-
1
let
is keyword, you shouldn't be naming (or attempting to name) variables that. I'm surprised Chrome even let (lol) you do that. – isick Commented Nov 20, 2019 at 20:30
2 Answers
Reset to default 10I'm assuming that
let = 1
is the same asvar let = 1
It declares a variable, but is not the same. The major distinction here is that by omitting a declaration like var
, let
, or const
, you're declaring this variable globally* (assuming you're not setting a previously-declared variable). This is what's known as an implicit global - a notorious code smell.
*In most cases, "global" would refer to the window
object, but this isn't always the case. For example, Node.js has its own global
namespace object that refers to the current module.
If so, shouldn't
let x = 2
be translated to1 x = 2
and therefore be an error?
No. let = 1
does not override the native functionality of the let
declaration/keyword. You've merely created a global variable of the same name. (Perhaps it goes without saying, but don't do this!)
And you didn't ask this specifically, but worth addressing:
Why am I allowed to do
let = 1
but notvar = 1
?
var
is a reserved keyword.
let
is a future reserved keyword, which means that currently it's only reserved in strict mode. That in mind, if you're trying to write code that will withstand the test of time, best not use let
as an identifier. As MDN states in the linked article, I'd imagine it'll be a reserved word sooner than later.
Backwards pability. let
is relatively new, therefore it is not a reserved keyword to not break old scripts using it as a variable name. That's why you can use let
as a variable name and not var
.
I'm assuming that let = 1 is the same as var let = 1.
No. It rather equals someothername = 1
and creates an implicit global variable which is very bad.
本文标签: Assigning quotletquot a value in JavascriptStack Overflow
版权声明:本文标题:Assigning "let" a value in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742356292a2459479.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论