var keyword
  1. var keyword was introduced with JavaScript.
  2. It has a function scope.
  3. It is hoisted.
function scope
Let us understand it with an example,
  1. //function scope
  2. function get(i){
  3. //block scope
  4. if(i>2){
  5. var a = i;
  6. }
  7. console.log(i);
  8. }
  9. //calling function
  10. get(3)
  11. //access variable outside function scope
  12. //it will give me an error
  13. console.log(i);
Output
3
Uncaught ReferenceError: i is not defined at window.onload
As you can see in the above example, I have declared a variable (var a = i) inside block but still I am able to access it outside the block (output = 3). If I try to access it outside function scope, it will give me an error (i is not defined).
Hoisting
When you declare a variable with var keyword, it will be automatically hoisted to the top of scope.
  1. //function scope
  2. function get(i){
  3. //printing i variable
  4. //value is undefined
  5. console.log(a);
  6. //declare variable after console but this variable hoisted to the top at //run time
  7. var a = i;
  8. //again printing i variable
  9. //value is 3
  10. console.log(a);
  11. }
  12. //calling function
  13. get(3)
Output
undefined
3
This happens behind the scene -
  1. //function scope
  2. function get(i){
  3. //a hoisted to the top
  4. var a;
  5. //if we don't give any value to variable, by default, value is undefined.
  6. //value is "undefined"
  7. console.log(a);
  8. //assigning value to a
  9. a = i;
  10. //value is 3
  11. console.log(a);
  12. }
  13. //calling function
  14. get(3)
let keyword
  1. let keyword was introduced in ES 6 (ES 2015).
  2. It has block scope.
  3. It is not hoisted.
Block scope
When you try to access let keyword outside block scope, it will give an error. let variable is available only inside the block scope.
  1. //declare a variable with var keyword
  2. var i = 4
  3. //block scope -start
  4. if(i>3)
  5. {
  6. //declare a variable with let keyword
  7. let j= 5;
  8. //declare a variable with var keyword
  9. var k = 8;
  10. //it will give me 5
  11. console.log("inside block scope (let)::"+ j);
  12. }
  13. //block scope -end
  14. //it will give me 8.
  15. //var variable are available outside block scope
  16. console.log("ouside block scope (var)::"+ k);
  17. //it will give me an error.
  18. //let variable are not available outside block scope
  19. console.log("ouside block scope (let)::"+ j);
Output
inside block scope (let)::5
ouside block scope (var)::8
Uncaught ReferenceError: j is not defined at window.onload
Hoisting
let keyword is not hoisted.
  1. //program doesn't know about i variable so it will give me an error.
  2. console.log(i);
  3. //declare and initilize let variable
  4. let i = 25;
Output
Uncaught ReferenceError: i is not defined at window.onload
If you have any questions, don't hesitate to contact.