Submodule 13.1: Introduction to ES6

  • Let vs Var
  • Advantages of let
  • Arrow functions

let vs var

In 2015, ES6 ( ECMAScript 6) was released. EcmaScript is not a different language, it is actually the official name for JavaScript.

The changes were done in order to improve the syntax and functionality of JavaScript.

One of the main changes was changing how we declare a variable by the replacement of var with let

So what is the difference between var and let?

When we declare a variable using var, this variable has function scope. With this, we mean that the variable defined is accessible in any part of the code. 

Let's see an example:

function myFunc () {
for (var i=0; i<10; i++) { 
// do something 
};
console.log(i);
}
myFunc ();

In this case, the outcome of console.log will be 10.

If we do the same thing using let:

function myFunc () {
for (let i=0; i<10; i++) { 
// do something 
};
console.log(i);
}
myFunc ();

the outcome will be: "Uncaught ReferenceError: i is not defined"

This is because in contrast with var, let has block scope. This means that the variable is available only inside the block where it was created.

In the next chapter we will learn what is the advantage of using block scope over function scope. 

Tip: Copy the above pieces of code and paste directly into the console, to see how they work.