Some more javascript quirks, function hoisting

What is alerted in each case?:

Q1.

function foo () {
    var bar = function() {
        return 3;
    };
    return bar();
    function bar () {
        return 8;
    }
}
alert(foo());

Q2.

function foo () {
    function bar () {
        return 3;
    }
    return bar();
    function bar () {
        return 8;
    }
}
alert(foo());

Q3.

function foo () {
    function bar () {
        return 3;
    }
    return bar();
    (function bar () {
        return 8;
    });
}
alert(foo());

Answer: 3, 8, 3.

Reason? In Q1, `function bar` gets hoisted to the top of function foo and then overwritten by the function expression of `var bar = …`. In Q2, both `function bar` are hoisted and the second overwrites the first. In Q3, the parenthesises turn `function bar` into a function declaration inside a function expression which prevents it from being hoisted.

Inspired by Function Declarations vs. Function Expressions and confirmed by Hoisting in JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s