Introduced in JavaScript 1.7
Summary
Declares a block scope local variable, optionally initializing it to a value.
let
keyword is only available to code blocks in HTML wrapped in a <script type="application/javascript;version=1.7">
block (or higher version). XUL script tags have access to these features without needing this special block.Syntax
let
definition:
let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];
let
expression:
let (var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]]) expression;
let
statement:
let (var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]]) statement;
Parameters
Parameter | Description |
---|---|
var1 , var2 , …, varN |
Variable name. It can be any legal identifier. |
value1 , value2 , …, valueN |
Initial value of the variable. It can be any legal expression. |
expression |
Any legal expression. |
statement |
Any legal statement. |
Description
let
allows you to declare variables, limiting its scope to the block, statement, or expression on which it is used. This is unlike the var
keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
Block scoping
let
declared variables are hoisted to the beginning of the enclosing block (see ECMAScript 6 exception below).
Redeclaration of the same variable in the same block scope raises a TypeError
.
if (x) { let foo; let foo; // TypeError thrown. }
However, function bodies do not have this limitation!
function do_something() { let foo; let foo; // This works fine. }
In ECMAScript 6, let
does not hoist the variable to the top of the block. If you reference a variable in a block before the let
declaration for that variable is encountered, this results in a ReferenceError
, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
function do_something() { console.log(foo); // ReferenceError let foo = 2; }
TypeError
if you do this, so you should avoid this practice!You may encounter errors in switch
statements because there is only one underlying block.
switch (x) { case 0: let foo; break; case 1: let foo; // TypeError for redeclaration. break; }
Examples
A let expression limits the scope of the declared variable to only that expression.
var a = 5; let(a = 6) alert(a); // 6 alert(a); // 5
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
var a = 5; var b = 10; if (a === 5) { let a = 4; // The scope is inside the if-block var b = 1; // The scope is inside the function console.log(a); // 4 console.log(b); // 1 } console.log(a); // 5 console.log(b); // 1
You can use the let keyword to bind variables locally in the scope of loops instead of using a global variable (defined using var) for that.
for (let i = 0; i<10; i++) { alert(i); // 0, 1, 2, 3, 4 ... 9 } alert(i); // i is not defined
When you are dealing with constructors you can use the let
statement in order to create a private interface without using closures:
/*\ |*| |*| :: A public and reusable API for constructors ... :: |*| \*/ let ( switchScope = function (oOwner, fConstructor) { return oOwner && oOwner.constructor === fConstructor ? oOwner : this; } ) { function buildIndoors (fConstructor) { const oPrivate = new fConstructor(this); this.getScope = oPrivate.getScope = switchScope.bind(this, oPrivate); return oPrivate; } } /*\ |*| |*| :: Use of the *let* statement in order to create a private interface without closures... :: |*| \*/ let ( /* "Secrets" is the constructor of the private interface */ Secrets = function Secrets (oPublic /* (the public interface) */) { /* setting a private property... */ this.password = Math.floor(Math.random() * 1e16).toString(36); /* you can also store the public interface into a private property... */ /* this.publicInterface = oPublic; */ alert("I\'m getting a public property from a private constructor...: somePublicProperty: " + oPublic.somePublicProperty); } ) { /* "User" is the constructor of the public interface */ function User (sNick) { /* setting a public property... */ this.somePublicProperty = "Hello World!"; const oPrivate = this.createScope(Secrets); /* (the private interface) */ /* setting a public property... */ this.user = sNick; alert("I\'m getting a private property from a public constructor...: password: " + oPrivate.password); } User.prototype.somePublicMethod = function () { const oPrivate = this.getScope(Secrets); /* (the private interface) */ alert("I\'m getting a public property from a public method...: user: " + this.user); alert("I\'m getting a private property from a public method...: password: " + oPrivate.password); oPrivate.somePrivateMethod(); }; Secrets.prototype.somePrivateMethod = function () { const oPublic = this.getScope(); /* (the public interface) */ alert("I\'m getting a public property from a private method...: user: " + oPublic.user); alert("I\'m getting a private property from a private method...: password: " + this.password); }; /* ...creating a mutual access... */ User.prototype.createScope = buildIndoors; } /* out of the *let* statement you have not access to the private interface! */ const johnSmith = new User("John Smith"); johnSmith.somePublicMethod();
See also
Block scope with let
(Merge into let
Statement)
There are several ways in which let
can be used to manage block scope of data and functions:
- The
let
statement provides a way to associate values with variables within the scope of a block, without affecting the values of like-named variables outside the block. - The
let
expression lets you establish variables scoped only to a single expression. - The
let
definition defines variables whose scope is constrained to the block in which they're defined. This syntax is very much like the syntax used forvar
. - You can also use
let
to establish variables that exist only within the context of afor
loop.
let
statement
The let
statement provides local scoping for variables. It works by binding zero or more variables in the lexical scope of a single block of code; otherwise, it is exactly the same as a block statement. Note in particular that the scope of a variable declared inside a let
statement using var
is still the same as if it had been declared outside the let
statement; such variables still have function scoping.
For example:
var x = 5; var y = 0; let (x = x+10, y = 12) { console.log(x+y); // 27 } console.log(x + y); // 5
The rules for the code block are the same as for any other code block in JavaScript. It may have its own local variables established using the let
declarations.
let
statement syntax, the parentheses following let
are required. Failure to include them will result in a syntax error.Scoping rules
The scope of variables defined using let
is the let
block itself, as well as any inner blocks contained inside it, unless those blocks define variables by the same names.
let
expressions
You can use let
to establish variables that are scoped only to a single expression:
var x = 5; var y = 0; console.log(let(x = x + 10, y = 12) x + y); console.log(x + y);
The resulting output is:
27 5
In this case, the binding of the values of x and y to x+10
and 12
are scoped solely to the expression x + y + "<br>\n"
.
Scoping rules
Given a let
expression:
let (decls) expr
There is an implicit block created around expr.
let
definitions
The let
keyword can also be used to define variables inside a block.
let
definitions, please consider adding them here.if (x > y) { let gamma = 12.7 + y; i = gamma * x; }
You can use let
definitions to alias pseudo-namespaced code in extensions. (See Security best practices in extensions.)
let Cc = Components.classes, Ci = Components.interfaces;
let
statements, expressions and definitions sometimes make the code cleaner when inner functions are used.
var list = document.getElementById("list"); for (var i = 1; i <= 5; i++) { var item = document.createElement("LI"); item.appendChild(document.createTextNode("Item " + i)); let j = i; item.onclick = function (ev) { alert("Item " + j + " is clicked."); }; list.appendChild(item); }
The example above works as intended because the five instances of the (anonymous) inner function refer to five different instances of variable j
. Note that it does not work as intended if you replace let
by var
or if you remove the variable j
and simply use the variable i
in the inner function.
Scoping rules
Variables declared by let
have as their scope the block in which they are defined, as well as in any sub-blocks in which they aren't redefined. 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:
function varTest() { var x = 31; if (true) { var x = 71; // same variable! alert(x); // 71 } alert(x); // 71 } function letTest() { let x = 31; if (true) { let x = 71; // different variable alert(x); // 71 } alert(x); // 31 }
The expression to the right of the equal sign is inside the block. This is different from how let
-expressions and let
-statements are scoped:
function letTests() { let x = 10; // let-statement let (x = x + 20) { alert(x); // 30 } // let-expression alert(let (x = x + 20) x); // 30 // let-definition { let x = x + 20; // x here evaluates to undefined alert(x); // undefined + 20 ==> NaN } }
At the top level of programs and functions, let
behaves exactly like var
does. For example:
var x = 'global'; let y = 'global'; console.log(this.x); console.log(this.y);
The output displayed by this code will display "global" twice.
let
definitions are likely to change in ES6.let
-scoped variables in for
loops
You can use the let
keyword to bind variables locally in the scope of for
loops. This is different from the var keyword in the head of a for loop, which makes the variables visible in the whole function containing the loop.
var i=0; for ( let i=i ; i < 10 ; i++ ) console.log(i); for ( let [name,value] in Iterator(obj) ) console.log("Name: " + name + ", Value: " + value);
Scoping rules
for (let expr1; expr2; expr3) statement
In this example, expr2, expr3, and statement are enclosed in an implicit block that contains the block local variables declared by let expr1
. This is demonstrated in the first loop above.
for (let expr1 in expr2) statement for each(let expr1 in expr2) statement
In both these cases, there are implicit blocks containing each statement. The first of these is shown in the second loop above.