var keyword
- var keyword was introduced with JavaScript.
- It has a function scope.
- It is hoisted.
function scope
Let us understand it with an example,
- //function scope
- function get(i){
- //block scope
- if(i>2){
- var a = i;
- }
- console.log(i);
- }
- //calling function
- get(3)
- //access variable outside function scope
- //it will give me an error
- 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.
- //function scope
- function get(i){
- //printing i variable
- //value is undefined
- console.log(a);
- //declare variable after console but this variable hoisted to the top at //run time
- var a = i;
- //again printing i variable
- //value is 3
- console.log(a);
- }
- //calling function
- get(3)
3
This happens behind the scene -
- //function scope
- function get(i){
- //a hoisted to the top
- var a;
- //if we don't give any value to variable, by default, value is undefined.
- //value is "undefined"
- console.log(a);
- //assigning value to a
- a = i;
- //value is 3
- console.log(a);
- }
- //calling function
- get(3)
let keyword
- let keyword was introduced in ES 6 (ES 2015).
- It has block scope.
- 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.
- //declare a variable with var keyword
- var i = 4
- //block scope -start
- if(i>3)
- {
- //declare a variable with let keyword
- let j= 5;
- //declare a variable with var keyword
- var k = 8;
- //it will give me 5
- console.log("inside block scope (let)::"+ j);
- }
- //block scope -end
- //it will give me 8.
- //var variable are available outside block scope
- console.log("ouside block scope (var)::"+ k);
- //it will give me an error.
- //let variable are not available outside block scope
- console.log("ouside block scope (let)::"+ j);
ouside block scope (var)::8
Uncaught ReferenceError: j is not defined at window.onload
Hoisting
let keyword is not hoisted.
- //program doesn't know about i variable so it will give me an error.
- console.log(i);
- //declare and initilize let variable
- let i = 25;
If you have any questions, don't hesitate to contact.

Join the conversation! Your thoughts help the community grow.