ES6 - Difference Between Var And Let

Overview
 
To declare the variables in JavaScript or TypeScript, we often use var or let. Here, we will discuss the differences between both of the declarations. 
 
var
 
When we declare variables using var:
  1. The declaration is processed before the execution.
  2. Variable will have function scope.
Code
  1. function CheckingScope() {  
  2.     var _scope = ‘Out’;  
  3.     console.log(_scope); // output Out  
  4.     if (true) {  
  5.         var _scope = ‘In’;  
  6.         console.log(_scope); // output In  
  7.     }  
  8.     console.log(_scope); // output In  
  9.  
In the above code, we can find that when the variable is updated inside the if block, the value of variable "_scope" is updated to “In” globally.
 
let
 
When we declare variables using let:
  1. Variable will have block scope. 
Code
  1. function CheckingScope() {  
  2.     var _scope = ‘Out’;  
  3.     console.log(_scope); // output Out  
  4.     if (true) {  
  5.         let _scope = ‘In’;  
  6.         console.log(_scope); // output In  
  7.     }  
  8.     console.log(_scope); // output Out  
In the above code, we can find that when the variable is updated inside the if block, the value of variable "_scope" is not updated globally.
 
Reference
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let