[Javascript] Hoisting in JavaScript
- Variable Hoisting
// Variable Hoisting var myVariable = 'Outer Value'; var fn = function(){ alert(myVariable); var myVariable = 'New Local Value'; }; fn();
In complier, the code will be:
var myVariable = 'Outer Value'; var fn = function(){ var myVariable = undefined; alert(myVariable ); myVariable = 'New Local Value'; } fn(); //So the alert result will be undefined
Function Declaration vs Function Expression
function fnDeclaration(){ return 'This is function declaration'; } var fnExpression = function(){ return 'This is function expression'; }
- Function Declaration Hoisting
// Function Declaration Hoisting function foo(){ function bar() { return 1; } return bar(); function bar() { return 2; } } alert(foo());
In complier, the code will be:
function foo(){ function bar(){ return 1; } function bar(){ return 2; } return bar(); // 2 will be alerted }
- Function Expression Hoisting
// Function Expression Hoisting function foo2(){ var bar = function() { return 1; }; return bar(); var bar = function() { return 2; }; } alert(foo2());
In complier, the code will be:
function foo2(){ var bar = undefined; //variable is hoisted var bar = undefined; bar = function(){ //function expression is not hoisted return 1; } return bar(); }
So, variable & function declaration will be hoisted! But the function expression is really not be hosited.