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?
Once you've declared a variable with var or let , you can reassign a new value to the variable in your programming flow. It is possible if the variable is accessible to assign a value. But with const , you can't reassign a new value at all.
The let keyword is used to declare variables in JavaScript. The var keyword can also be used to declare variables, but the key difference between them lies in their scopes. var is function scoped while let is block scoped - we will discuss this in more detail later.
Use let when you know that the value of a variable will change. Use const for every other variable. Do not use var.
I'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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With