Dec 14, 2016

Hoisting in Javascript

You might have heard of Flag hoisting , but what the fuck is hoisting in JavaScript ?
There are two types of hoisting, variable hoisting and function hoisting.


Variable hoisting :


By default JavaScript move all declarations to the beginning of the current scope or current function.

Example 1 : Variable hoisting in very outer scope

x = 5; // Assign/defining 5 to x
console.log(x)                  
var x; // Declare x 
BUT this is How it will be Executed
var x; // Declare x 
x = 5; // Assign/defining 5 to x
console.log(x)   
Observation : See the difference var x; // Declare x   is set to the beginning for scope  

Example 2 : Variable hoisting inside function

function foo() {
    console.log(tmp); // undefined
    if (false) {
        var tmp = 3;  // (1)
    }
}
Internally, the function is executed like this:
function foo() {
    var tmp;  // hoisted declaration
    console.log(tmp);
    if (false) {
        tmp = 3;  // assignment stays put
    }
}
Observation :
    1 : see variable declaration is moved to the beginning of function;
    2 : It also Means variable is moved to beginning of functions scope in which it is declared.And scoping in JavaScript is done only by functions


Function hoisting :


By default JavaScript moves all declarations to the beginning of the current scope or current function.

Example 1 : function hoisting

function foo(){
    function bar() {
        return 3;
    }
    return bar();
    function bar() {
        return 8;
    }
}
alert(foo());
Above Code  will be executed as
function foo(){
    function bar() {
        return 3;
    }
    function bar() {
        return 8;
    }
    return bar();
}
alert(foo());
So according to javascript hoisting nature first bar function will be overridden by second and output will be 8

Output : 8

Example 2 : functions are hoisted but not function expression; So below code contains function function declaration that contains two function expression .So this code will execute as it is.

function foo(){
    var bar = function() {   //function expression
        return 3;
    };
    return bar();
    var bar = function() {   //function expression
        return 8;
    };
}
alert(foo());
Output : 3

Example 3 : JavaScript hoists function declaration and not function expressions;So below is function declaration that includes two function expression and JavaScript executes as it is like in example 2 in function hoisting

function foo(){
    return bar();
    var bar = function() {
        return 3;
    };
    var bar = function() {
        return 8;
    };
}
alert(foo());
Output : bar is not a functiona as javascript does not hoists function expression

No comments :

Post a Comment