function foo(){
// ....
}
creates new Function object, and assignees name foo to it. It is still no where called, just created, so any return statement will not be triggered.
When inside this function you create new Functions, like
function foo(){
function bar() {
return 3;
}
return 4;
}
// after you execute foo
console.log(foo()); // will log 4
But very important that inside this lexical scope, function bar is created, but no where executed. See also Lexical scope
But when you have this
function foo(){
function bar(){
return 3;
}
function bar() {
return 8;
}
return bar();
}
// after you execute foo
console.log(foo()); // will log 8
When you execute function foo inside global scope, it creates Function object named bar, then it creates new Function object named bar, the old one is redefined, same as assigning new value to variable, value changes, but in this context function body that is assigned to Function name has change.
Because your function foo has return keyword, it returns that value. Value that it returns is value that returns function bar, as return bar(); will execute function bar and return value it receives from function bar, in example it is value 8.
Compare variable redefinition with function redefinition
var a;
a = "some string";
a = 5; // a has value 5, no mater older values
// same goes for functions
function bar(){ .... }
function bar(){ .... }
function bar(){ .... }
// invoke bar
bar(); // last function bar will be executed, no mater other function's bar definitions
x = 3thenx = 8. So why are you expectingx == 3?x = 3. The first function is never called as it's overwritten by the second one.bar = 3thenbar = 8thenreturn bar... is exactly what I said and what is written out above.bar()function doesn't exist as it's overridden by the second. Literally, it is never called so there is never a return value of 3. It's 8 and only 8.