Menu

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

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: