ES6 / ES2015 Let & Const

let is the new var

These are the new kids on the block. They really are. No longer are you going to be in a scope muddle because unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope, using let you can declare variables that are limited in scope to the block, statement, or expression on which it is used.

Nifty eh?

One time only variables with const

Constants can be global or local to the function in which it is declared. But crucially the value of a constant cannot change through re-assignment, and cannot be re-declared.

A constant cannot share its name with a function or a variable in the same scope.

Let's take a look at this.

let x;

function myFunction() {  
  // This is okay, we've got a block scoped name
  const x = 'foo';

  // This will throw an error,
  // we've already declared `x` in this block with a `const`
  x = 'bar';
}

// This is okay, we declared it with `let`
x = 'foo';

// This will throw an error,
// we've already declared `x` in this block with a `let`
let x = 'bar';  

Scoping rules

This from MDN should make it clearer.

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 = 10;
  if (true) {
    var x = 20;  // same variable!
    console.log(x);  // 20
  }
  console.log(x);  // 20
}

function letTest() {  
  let x = 10;
  if (true) {
    let x = 20;  // different variable
    console.log(x);  // 20
  }
  console.log(x);  // 10
}

So as you can see, there's a little bit more going on with let and const over a var. In theory you should get into less of a muddle with which scope your var is in.

Got some questions? Leave a comment below.