Assigning "let" a value in Javascript

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 compability. 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.

Tags:

Javascript