let – JavaScript | MDN
let
allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var
keyword, which declares a variable globally, or locally to an entire function regardless of block scope. The other difference between var
and let
is that the latter can only be accessed after its declaration is reached (see temporal dead zone). For this reason, let
declarations are commonly regarded as non-hoisted.
Just like const
the let
does not create properties of the window
object when declared globally (in the top-most scope).
An explanation of why the name let
was chosen can be found in the linked StackOverflow answer.
Many issues with let
variables can be avoided by declaring them at the top of the scope in which they are used (doing so may impact readability).
Unlike var
, let
begins declarations, not statements. That means you cannot use a lone let
declaration as the body of a block (which makes sense, since there’s no way to access the variable).
if
(
true
)
let
a =
1
;