ECMA6 ? Why ?

ECMAScript 2015, also known as ES6, introduced many changes to JavaScript. We will look into some of the most common features and syntax additions comparing them in ES6.

We will start with the difference in variable declaration in ES6.

Variable Declaration (var vs let vs const)

Let us start with the concepts of scoping. After we get an idea about scoping we will take it further to highlight the differences between let, var, and const in JavaScript.

Scope

Scope defines where variables and functions are accessible inside of your program. In JavaScript, there are two kinds of scope - global scope, and function scope. What that means is if you create a variable with var, that variable is “scoped” to the function it was created in and is only accessible inside of that function or, any nested functions.

function getDate () {
  var date = new Date();

  return date;
}

getDate();         // Sun Mar 10 2019 14:01:44 GMT+0500
console.log(date); // Uncaught ReferenceError: date is not defined

Hoisting

Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function). Lets take an example.

function getX () {
  var x = 10;

  if(x)
  {
    var x = 4;
  }

  console.log(x);
}

getX();         // 4

The problem with the above function is that if I redecalared a variable it will override the same variable in its outer scope. This can be problematic because I would never want to change the value of my outer scope variable with an internal local scope variable.

What can we do ?

We can use let to limit the value to an inner scope

function getX () {
  var x = 10;

  if(x)
  {
    let x = 4;
  }

  console.log(x);
}
getX();         // 10

Bang! Problem solved!!

Stop Tampering of Constant Values

Now lets assume a case where we want to make a value constant. Lets assume there is a function which returns the value of pie which is 3.14.

function getPie () {
  var constant = 3.14;

  if(constant)
  {
    constant = 0;
  }

  console.log(constant);
}
getPie();         // 0

The above function returns 0 i.e. if we try to change the value of pie we can do it.

What can we do ?

We can use const to stop assignment of pie.

function getPie () {
  const constant = 3.14;

  if(constant)
  {
    constant = 0;
  }

  console.log(constant);
}
getPie();         // TypeError: Assignment to constant variable.

This table provides the summary of the above discussion.

Keyword Scope Hoisting Can Be Reassigned Can Be Redeclared
var Function scope Yes Yes Yes
let Block scope No Yes No
const Block scope No No No

To sum up the discussion, you should use let for local variables and const for constant values you wont have to handle the problems of scoping, hoisting, assignment and redeclaration.