The two new keywords in ES6 || ES2015 includes the keywords let and const which can be used for declaring and defining values to create variables similar to var.

To understand the difference between the three lets first talk about scope.

 

Scopes in JavaScript


As we know JavaScript has two scopes namely Global Scope and Function Scope.

A variable is said to get defined with Function Scope when it is defined in a function like this:

function foo(){
    var bar; // Function Scoped
    function fun(){
       return bar;
    }
}

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

 

The variable bar can be accessible inside the function and any nested functions inside foo.

And when a variable is defined outside a function, it is bound to the Global Scope. (Variables created without using var are globally scoped).
 

function foo(){
    var bar;
}

var baz; // Global Scoped

 

A /sort-of/ problem with var

 

Consider the following code:

function double(array){

  var doubledArray = []

  for(var i = 0; i < array.length; i++){
    var doubledValue = array[i] * 2 
    doubledArray.push(doubledValue)
  }

  console.log(i) // 3
  console.log(doubledValue) //6
  return doubledArray

}

console.log(double([1,2,3])) // [2,4,6]

We can see that the value of and doubledValue are accessible outside of for loop because they are created with var and are function scoped thus making it accessible anywhere inside that function. This may cause some harm when some other piece of code inside the same function uses the same variable name or changes the value of the variable. How do we eliminate that?

Here enters let and block scope.

Block scope is nothing but the code inside curly braces { } like and if statement or a loop. So by using let instead of var in our for loop, we can limit scope to the loop itself.

function double(array){

  var doubledArray = []

  for(var i = 0; i < array.length; i++){
    var doubledValue = array[i] * 2 
    doubledArray.push(doubledValue)
  }

  console.log(i) // ReferenceError: i is not defined
  console.log(doubledValue) // ReferenceError: doubledValue is not defined
  return doubledArray

}

console.log(double([1,2,3])) // [2,4,6]

 

Noicee!!

Remember, that JavaScript hoists var and let, the difference being - var when hoisted is assigned undefined and let when hoisted gives us ReferenceError.

const is Mutable, Once a const variable is declared and assigned a value it cannot be changed whatsoever.

const foo; //SyntaxError: Missing initializer in const declaration
const foo = "bar"

Always assign value to a const variable!

blog comments powered by Disqus