Function Hoisting In JavaScript


When writing functions in Javascript it can be a little confusing. Hopefully by walking through a few examples we can see the nature of hoisting in Javascript to better understand it’s behaviour.

In Javascript the following functions are hoisted:

function foo() {
    function bar() { return 1; }
    return bar();
    function bar() { return 2; }
}
console.log( foo() ); // => 2 

Notice how within the foo() function that there’s a return statement between the two bar() functions. Surely the second bar() function would never run, however, as our console.log reports it indeed does!

Why?

The reason for this is that the functions are hoisted within foo() one after the other and then the return statement is placed underneath. It would be equivalent to writing:

function foo() {
    function bar() { return 1; }
    function bar() { return 2; }
    return bar();
}
console.log( foo() ); // => 2

What happens if we tried the following – we create a bar variable and call an anonymous function?

Like so:

function foo() {
    var bar = function() { return 1; };
    return bar();
    var bar = function() { return 2; };
}
console.log( foo() ); // => 1 

Why do we get 1 in this result?

Here the functions aren’t hoisted and instead the way the function operates is as follows:

function foo() {
    var bar = undefined; // first bar declared
    var bar = undefined; // second bar declared
    bar = function() { return 1; };
    return bar();
    bar = function() { return 2; }; // this never gets parsed as we’ve hit the return statement above
}

Now we never get to that second function due to the return statement.

Recent Posts