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?

Share Improve this question edited Nov 20, 2019 at 20:34 Igor 62.3k10 gold badges111 silver badges180 bronze badges asked Nov 20, 2019 at 20:28 RaisenRaisen 4,4952 gold badges28 silver badges43 bronze badges 1
  • 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
Add a ment  | 

2 Answers 2

Reset to default 10

I'm assuming that let = 1 is the same as var 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 to 1 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 not var = 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