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)

Join the conversation! Your thoughts help the community grow.