HOISTING in JavaScript

HOISTING in JavaScript :All JavaScript variables are hoist at the top of the scope (function) in which they are defined. To understand it consider the code snippet shows below,

var foo = "foo";
console.log(foo);

Above code will print foo in the console.Now let us go ahead and add a function as shown –

var foo = "foo";
console.log(foo);
(function () {
    console.log(foo);
}
)();

foo will be printed twice on the console. We saw that a variable defined outside a function scope or in global function scope can be used inside other functions. Let us go and modify the function as shown below,

var foo = "foo";
console.log(foo); // print foo
 (function () {
 
    console.log(foo); // print undefined
    var foo = "zoo";
}
)();

To be surprised now second console statement will print the value undefined.There are the reasons of that,
1) We have again declared foo inside the anonymous function.
2) JavaScript always hoist a variable declaration at the top of the scope. It only hoist the declaration not the initialization.

In actual, above anonymous function can be look like as. Declaration has been moved to the top of the function scope, whereas initialization is done at the place variable is declared.

(function(){
  var foo;
  console.log(foo); //Print undefined
  foo = 'zoo';
  console.log(foo); //Print zoo
}
)();

In above function, we are trying to access variable foo before it is initialized and that’s the reason we are getting undefined value printed. There are two types of scoping in the JavaScript,

1) Function scope.
2) Global scope.

Always a variable is hoisted at either the top of the function scope or global scope. When you use var to declare a variable inside a function, then that variable is inside that particular function scope. When you declare a variable without using var, it is always in the global scope.

More Info : Hoisting Simplified

About

My Name is Dileep Singh, Noder, Javascript Lover & NoSql Developer, Fitness Freak, Love to travel new places, learning photography & Music Manic ♯ ♩ ♬

Posted in Javascript