Function Declarations vs. Function Expressions

Lets start with a short quiz. What is alerted in each case?:

Question 1:

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

Question 2:

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

Question 3:

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

Question 4:

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

If you didn’t answer 8, 3, 3 and [Type Error: bar is not a function] respectively, read on… (actually read on anyway ;-) )

Continue reading