Sunday, March 4, 2018

Difference between let const and var

There are three types of variable declaration is possible in ES6. Each have some different scope so developer should use that correct situation.


1. Variable by using var

Before Es6 came , var was used at all time. But after ES6 , developer have choose let. However, still developers are using both let and var.

Simple example, var name="test";

Remember, let and var have huge difference there.

See the below example,

(function (){
  for(var i = 0; i<10; i++) {
    console.log(i)
  }
})(); // Print 0 to 9

console.log(i); // Print 10

From the above code loop running and printing value 0, 1, 2... 9. But after that it will print 10 also. Because still variable i have scope. But if you use let here instead of var, it will error.


2. Variable by using let

Use let keyword to create variable. Its a block level scope.

Example:

let message;                 // Just declaration using let
message = 'Hello!';
let name = 'John', age = 19; //multiple variables
alert(message); // alert show message value


let- block level scope
Example below,


(function (){
  for(let i = 0; i<10; i++) {
    console.log(i)
  }
})(); // Print 0 to 9

console.log(i); // i is not defined

Hope now you have understand var and let difference.

3. Variable by using const

If you want any variable should be constant, go for this. Once assigned, we can not reassign.

Example :


const FixedValue =10;
  console.log(FixedValue);  //Print 10
  FixedValue =20;           //throws Error
  console.log(FixedValue); 

Above code, FixedValue assigned already and trying to reassign throwing an error.



Conclusion:

So based on your situation scope level choose the right one. Better one is let than var and const will be choose for constant.









No comments:

Post a Comment