let

The let statement declares a block scope local variable, optionally initializing it to a value.

Syntax

let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];

Parameters

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.

Description

let allows you to declare variables that are limited in 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.

An explanation of why the name "let" was chosen can be found here.

Scoping rules

Variables declared by let have as their scope the block in which they are defined, 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:

function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}
function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}

Cleaner code in inner functions

let sometimes makes the code cleaner when inner functions are used.

var list = document.getElementById('list');
for (let i = 1; i <= 5; i++) {
  let item = document.createElement('li');
  item.appendChild(document.createTextNode('Item ' + i));
  item.onclick = function(ev) {
    console.log('Item ' + i + ' is clicked.');
  };
  list.appendChild(item);
}
// to achieve the same effect with 'var'
// you have to create a different context
// using a closure to preserve the value
for (var i = 1; i <= 5; i++) {
  var item = document.createElement('li');
  item.appendChild(document.createTextNode('Item ' + i));
  (function(i){
    item.onclick = function(ev) {
      console.log('Item ' + i + ' is clicked.');
    };
  })(i);
  list.appendChild(item);
}

The example above works as intended because the five instances of the (anonymous) inner function refer to five different instances of the variable i. Note that it does not work as intended if you replace let with var, since all of the inner functions would then return the same final value of i: 6. Also, we can keep the scope around the loop cleaner by moving the code that creates the new elements into the scope of each loop.

At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example:

var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined

Emulating private members

In dealing with constructors it is possible to use the let statement to share one or more private members, through use of closures:

var SomeConstructor;
{
  let privateScope = {};
  SomeConstructor = function SomeConstructor() {
    this.someProperty = 'foo';
    privateScope.hiddenProperty = 'bar';
  }
  SomeConstructor.prototype.showPublic = function() {
    console.log(this.someProperty); // foo
  }
  SomeConstructor.prototype.showPrivate = function() {
    console.log(privateScope.hiddenProperty); // bar
  }
}
var myInstance = new SomeConstructor();
myInstance.showPublic();
myInstance.showPrivate();
console.log(privateScope.hiddenProperty); // error

This technique only provides "static" private state - in the above example, all instances of SomeConstructor will share the same privateScope.

Temporal Dead Zone and errors with let

Redeclaring the same variable within the same function or block scope raises a SyntaxError.

if (x) {
  let foo;
  let foo; // SyntaxError thrown.
}

In ECMAScript 2015, let bindings are not subject to Variable Hoisting, which means that let declarations do not move to the top of the current execution context. Referencing the variable in the block before the initialization results in a ReferenceError (contrary to a variable declared with var, which will just have the undefined value). The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

function do_something() {
  console.log(bar); // undefined
  console.log(foo); // ReferenceError
  var bar = 1;
  let foo = 2;
}

You may encounter errors in switch statements because there is only one block.

let x = 1;
switch(x) {
  case 0:
    let foo;
    break;
  case 1:
    let foo; // SyntaxError for redeclaration.
    break;
}

However, it's important to point out that a block nested inside a case clause will create a new block scoped lexical environment, which will not produce the redeclaration errors shown above.

let x = 1;
switch(x) {
  case 0: {
    let foo;
    break;
  }  
  case 1: {
    let foo;
    break;
  }
}

Another example of temporal dead zone combined with lexical scoping

Due to lexical scoping, the identifier "foo" inside the expression (foo + 55) evaluates to the if block's foo, and not the overlying variable foo with the value of 33.
In that very line, the if block's "foo" has already been created in the lexical environment, but has not yet reached (and terminated) its initialization (which is part of the statement itself): it's still in the temporal dead zone.

function test(){
   var foo = 33;
   if (true) {
      let foo = (foo + 55); // ReferenceError
   }
}
test();

This phenomenon may confuse you in a situation like the following. The instruction let n of n.a is already inside the private scope of the for loop's block, hence 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"), which is still in the temporal dead zone since its declaration statement has not been reached and terminated.

function go(n) {
  // n here is defined!
  console.log(n); // Object {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.

var a = 1;
var b = 2;
if (a === 1) {
  var a = 11; // the scope is global
  let b = 22; // the scope is inside the if-block
  console.log(a);  // 11
  console.log(b);  // 22
} 
console.log(a); // 11
console.log(b); // 2

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Let and Const Declarations' in that specification.
Standard Initial definition. Does not specify let expressions or let blocks.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Let and Const Declarations' in that specification.
Living Standard  

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support 41.0 12 44 (44) 11 17 10.0
Temporal dead zone ? 12 35 (35) 11 ? ?
Allowed in sloppy mode 49.0 ? 44 (44) ? ? ?
Feature Android Android Webview Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support ? 41.0 (Yes) 44.0 (44) ? ? 10.0 41.0
Temporal dead zone ? ? (Yes) 35.0 (35) ? ? ? ?
Allowed in sloppy mode No support 49.0 ? 44 (44) ? ? ? 49.0

Firefox-specific notes

  • Prior to SpiderMonkey 46 (Firefox 46 / Thunderbird 46 / SeaMonkey 2.43), a TypeError was thrown on redeclaration instead of a SyntaxError (bug 1198833, bug 1275240).
  • Prior to SpiderMonkey 44 (Firefox 44 / Thunderbird 44 / SeaMonkey 2.41), let was only available to code blocks in HTML wrapped in a <script type="application/javascript;version=1.7"> block (or higher version) and had different semantics.
  • Support in Worker code is hidden behind the dom.workers.latestJSVersion flag (bug 487070). With version free let, this flag is going to be removed in the future (bug 1219523).

See also