Friday, April 14, 2017

Charlies angles for declaring variables in ES6



All these days we were able to use only var for declaring variables. Now we have the charlies angles options for declaring variables . What I mean is we have three ways of declaring variables.

Previously we had only 2 scopes. function scope and global scope. global scope is assigned if we do not declare var


Edit in plnkr

var

Function scope
If we use var within an condition it would still be available to the function.

In the example we changed the firstname from "Prathap to Atharv". However it changed the parent scope and we get Atharv outside the if condition.

//example to show function scope in javascript
function varTest()
{
//parent scope
 var firstName ="Prathap";

 if(firstName ==="Prathap")
 {
      //try to create a block scope using var
      var firstName="Atharv";
      console.log("block scope:"+ firstName) // op :Atharv
     
 }
 console.log("Parent scope:"+ firstName) // op :Should be Prathap. 
 //However the inner variable has flipped the parent variable and we get Atharv
}

//function call
varTest();

Output

C:\Development\NodeProjects\vanilanode>node letVarConst.js
block scope:Atharv
Parent scope:Atharv

let

Similar to var , but has block scope.
In this example we are using let withing the if condition. In the ouput we see that the parent scope is retained.

function letTest()
{
//parent scope
 let firstName ="Prathap";

 if(firstName ==="Prathap")
 {
      //try to create a block scope using var
      let firstName="Atharv";
      console.log("block scope:"+ firstName) // op :Atharv
     
 }
 console.log("Parent scope:"+ firstName) // op :Should be Prathap. 
 //Parent scope is retained
}
Output
C:\Development\NodeProjects\vanilanode>node letVarConst.js
block scope:Atharv
Parent scope:Prathap

Difference between block vs let



const (Similar to let)

Cannot be reassigned. its not immutable programming. It is similar to let however it cannot be reassigned.

//example to show function scope in javascript using const
function constTest()
{
//parent scope
 const firstName ="Prathap";
  firstName ="TH"
 if(firstName ==="Prathap")
 {
      //try to create a block scope using var
      const firstName="Atharv";
      console.log("block scope:"+ firstName) // op :Atharv
     
 }
 console.log("Parent scope:"+ firstName) // op :Should be Prathap. 
 //Parent scope is retained
}

Output
C:\Development\NodeProjects\vanilanode>node  letVarConst.js
C:\Development\NodeProjects\vanilanode\letVarConst.js:37
  firstName ="TH"
            ^

TypeError: Assignment to constant variable.

No comments:

Post a Comment