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 get(i){
-
- if(i>2){
- var a = i;
- }
- console.log(i);
- }
-
- get(3)
-
-
-
- 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 get(i){
-
-
- console.log(a);
-
-
- var a = i;
-
-
-
- console.log(a);
- }
-
- get(3)
Output
undefined
3
This happens behind the scene -
-
- function get(i){
-
- var a;
-
-
- console.log(a);
-
-
- a = i;
-
-
- console.log(a);
- }
-
- get(3)
- 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.
- with var keyword
- var i = 4
-
- if(i>3)
- {
-
- let j= 5;
-
-
- var k = 8;
-
- console.log("inside block scope (let)::"+ j);
- }
-
-
-
-
- console.log("ouside block scope (var)::"+ k);
-
-
-
- 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.
-
- console.log(i);
-
- let i = 25;
Output
Uncaught ReferenceError: i is not defined at window.onload
If you have any questions, don't hesitate to contact.