ES6 let & const

If you are familiar with JavaScript, you have probably known the term scope. If you are familiar with other languages, you would know that a scope of a variable is to the nearest block – block scope. But JavaScript is different. A variable created with var will be scoped to the nearest parent function.

let

We can imagine that let is a new var statement. But there is no need to replace every var with let, but only when you require a block scoped variables.

Firstly, imagine and old way (and still valid) to declare a new variable in your JS code using ES5:

var foo = 1;

console.log(foo); // 1

{
  var bar = 2;
  console.log(bar); // 2
}

function fn() {
  console.log(foo); // undefined
  var foo = 3;
  console.log(foo); // 3
}

fn();

console.log(foo); // 1
console.log(bar); // 2

Now lets write the same code using let:

let foo = 1;

console.log(foo); // 1

{
  let bar = 2;
  console.log(bar); // 2
}

function fn() {
  console.log(foo); // undefined
  var foo = 3;
  console.log(foo); // 3
}

fn();

console.log(foo); // 1
console.log(bar); // ReferenceError: bar is not defined

As we can see, this time only variable foo is declared as a global. let gives us a way to declare block scoped variables, which is undefined outside it.

REPL

You can use Babel or Traceur to transpile ES6 code.

const

const is single-assignment and like a let, block-scoped declaration.

{
 const PI = 3.141593;
 PI = 3.14; // throws "PI" is read-only
}

console.log(PI); // throws ReferenceError: PI is not defined

const cannot be reinitialized. It will throw an Error when we try to assign another value.

Let’s look for the equivalent in ES5:

var PI = (function () {
  var PI = 3.141593;
  return function () { return PI; };
})();

Be first to comment

Leave a Reply