let
The let
declaration declares a block-scoped local variable, optionally initializing it to a value.
Try it
Syntax
js
let name1;
let name1 = value1;
let name1 = value1, name2 = value2;
let name1, name2 = value2;
let name1 = value1, name2, /* …, */ nameN = valueN;
Parameters
nameN
-
The names of the variable or variables to declare. Each must be a legal JavaScript identifier.
valueN
Optional-
For each variable declared, you may optionally specify its initial value to any legal JavaScript expression.
The destructuring assignment syntax can also be used to declare variables.
js
let { bar } = foo; // where foo = { bar: 10, baz: 12 };
// This creates a variable with the name 'bar', which has a value of 10
Description
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).
js
if (true) let a = 1; // SyntaxError: Lexical declaration cannot appear in a single-statement context
Examples
Scoping rules
Variables declared by let
have their scope in the block for which they are declared, as well as in any contained sub-blocks. In this way, let
works very much like var
. The main difference is that the scope of a var
variable is the entire enclosing function:
js
function varTest() {
var x = 1;
{
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
{
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
At the top level of programs and functions, let
, unlike var
, does not create a property on the global object. For example:
js
var x = "global";
let y = "global";
console.log(this.x); // "global"
console.log(this.y); // undefined
Redeclarations
Redeclaring the same variable within the same function or block scope raises a SyntaxError
.
js
if (x) {
let foo;
let foo; // SyntaxError thrown.
}
You may encounter errors in switch
statements because there is only one block.
js
let x = 1;
switch (x) {
case 0:
let foo;
break;
case 1:
let foo; // SyntaxError for redeclaration.
break;
}
A block nested inside a case clause will create a new block scoped lexical environment, avoiding the redeclaration errors shown above.
js
let x = 1;
switch (x) {
case 0: {
let foo;
break;
}
case 1: {
let foo;
break;
}
}
If you're experimenting in a REPL, such as the Firefox web console (Tools > Web Developer > Web Console), and you run two let
declarations with the same name in two separate inputs, you may get the same re-declaration error. See further discussion of this issue in Firefox bug 1580891. The Chrome console allows let
re-declarations between different REPL inputs.
Temporal dead zone (TDZ)
A let
or const
variable is said to be in a "temporal dead zone" (TDZ) from the start of the block until code execution reaches the line where the variable is declared and initialized.
While inside the TDZ, the variable has not been initialized with a value, and any attempt to access it will result in a ReferenceError
. The variable is initialized with a value when execution reaches the line of code where it was declared. If no initial value was specified with the variable declaration, it will be initialized with a value of undefined
.
This differs from var
variables, which will return a value of undefined
if they are accessed before they are declared. The code below demonstrates the different result when let
and var
are accessed in code before the line in which they are declared.
js
{
// TDZ starts at beginning of scope
console.log(bar); // undefined
console.log(foo); // ReferenceError
var bar = 1;
let foo = 2; // End of TDZ (for foo)
}
The term "temporal" is used because the zone depends on the order of execution (time) rather than the order in which the code is written (position). For example, the code below works because, even though the function that uses the let
variable appears before the variable is declared, the function is called outside the TDZ.
js
{
// TDZ starts at beginning of scope
const func = () => console.log(letVar); // OK
// Within the TDZ letVar access throws `ReferenceError`
let letVar = 3; // End of TDZ (for letVar)
func(); // Called outside TDZ!
}
The TDZ and typeof
Using the typeof
operator for a let
variable in its TDZ will throw a ReferenceError
:
js
// results in a 'ReferenceError'
console.log(typeof i);
let i = 10;
This differs from using typeof
for undeclared variables, and variables that hold a value of undefined
:
js
// prints out 'undefined'
console.log(typeof undeclaredVariable);
TDZ combined with lexical scoping
The following code results in a ReferenceError
at the line shown:
js
function test() {
var foo = 33;
if (foo) {
let foo = foo + 55; // ReferenceError
}
}
test();
The if
block is evaluated because the outer var foo
has a value. However due to lexical scoping this value is not available inside the block: the identifier foo
inside the if
block is the let foo
. The expression foo + 55
throws a ReferenceError
because initialization of let foo
has not completed — it is still in the temporal dead zone.
This phenomenon can be confusing in a situation like the following. The instruction let n of n.a
is already inside the private scope of the for...of
loop's block. So, the identifier n.a
is resolved to the property a
of the n
object located in the first part of the instruction itself (let n
). This is still in the temporal dead zone as its declaration statement has not been reached and terminated.
js
function go(n) {
// n here is defined!
console.log(n); // { a: [1, 2, 3] }
for (let n of n.a) {
// ^ ReferenceError
console.log(n);
}
}
go({ a: [1, 2, 3] });
Other situations
When used inside a block, let
limits the variable's scope to that block. Note the difference between var
, whose scope is inside the function where it is declared.
js
var a = 1;
var b = 2;
{
var a = 11; // the scope is global
let b = 22; // the scope is inside the block
console.log(a); // 11
console.log(b); // 22
}
console.log(a); // 11
console.log(b); // 2
However, this combination of var
and let
declarations below is a SyntaxError
because var
not being block-scoped, leading to them being in the same scope. This results in an implicit re-declaration of the variable.
js
let x = 1;
{
var x = 2; // SyntaxError for re-declaration
}
Specifications
Specification |
---|
ECMAScript Language Specification # sec-let-and-const-declarations |
Browser compatibility
BCD tables only load in the browser