Variable Hoisting In JavaScript

12 / Oct / 2014 by Sakshi Tyagi 0 comments

Javascript handles function and variable declartions quite differently and you must have got stuck in one of the awkard scenarios due to it.

First of all, you should be familiar with Scoping in JavaScript. If you are, then you would know already that JavaScript only has function scopes and no block scopes.

var a = 'hello';
console.log(a);
if(a)
{    console.log(a);
    a = 'javascript';
 }
console.log(a);

The result is:

hello
hello
javascript

As we can see in the above example, the if block doesn’t create a new scope.

Lets go into the concept of Hoisting now. Hoisting is a way in which JavaScript deals with variable and function declarations. What actually the JavaScript interpreter does is, it pushes all your Function and Variable declarations to the top of the containing scope.

Lets understand this with a simple example:

function sum() {
    calculate();
    var a = 10;
    var b = 20;
}

//Now this function will be interpreted as below

function sum() {
    var a, b;
    calculate();
    a = 10;
    b = 20;
}

Lets try some code here:

function calculate() {
    sum();
    multiply();
    var a = 10;
    function sum(){
        console.log(a + b);
    }    
    var b = 20;
    var multiply = function() {
        console.log(a * b);
    }
}
calculate();

The above code will throw an error : undefined is not a function. Lets see how this function is interpreted.

function calculate() {
    var a, b, multiply;
    function sum(){
        console.log(a + b);
    }
    sum();
    multiply();
    a = 10;
    b = 20;
    multiply = function() {
        console.log(a * b)
    }        
}

As we can see, only the left handside of the declarations is hoisted, but that is not the case with function declarations written as sum method.

The other way of declaring functions is as method multiply, in this case though the interpreter only takes the left hand side name. This results in an error undefined is not a function as multiply is undefiend at the time of function call.

This is all about JavaScript Hoisting in brief.
Hope it helps you, hoisting your own flag in JavaScript.

FOUND THIS USEFUL? SHARE IT

Leave a comment -