Hoisting is Pre-Scope in JavaScript. Only declarations themselves are hoisted, while assignments not.
For Expample-
exp();
function exp(){
console.log(a);
var a=1;
}
In above code snippet there will be no error but the output will be undefined because JavaScript see this code as-
function exp(){
var a;
console.log(a);
a=2;
}
exp();
The declaration comes first and then assignment comes. Js Engine compile JS code before it interprets.
Compilation phase has to find associate all declarations with their appropriate scopes.
Like you think var a=1; as one statement while JS thinks it as two like-
var a; // compilation phase a=1; // execution phase
Now we will take another example-
exp();
var exp= function abc(){
};
It will not throw the reference error but it has no value yet. So exp() is trying to invoke undefined value which is TypeError.
Lets take one more example-
exp();
abc();
var exp= function abc() {};
It will interpret as-
var exp;
exp();
abc();
exp = function(){
var abc= --self--
}
// Uncaught TypeError: exp is not a function
All declaration in a scope regardless of where they appear, are processed first before code execution. Declaration of variable and function being “moved” to top of their respective scopes which we call hoisting.
NOTE- Declarations hoisted but assignments are not hoisted.

Be the first to comment.