Yep. I think what was happening is the following:
Functions declared with function test(...) { ... }
are hoisted to the top of current scope. So both definitions of your function using that syntax were hoisted to the top, but the second one defined overwrote the first one, thus the result 'baz.'
Function expressions are not hoisted, e.g. test = function (...) {...}
. So when you reassigned the identifier test
to that function expression, it became the value for test
for the remainder of your script.
As pointed out already, you cannot overload vars or functions in JavaScript. You can overwrite vars with new values, which is what you did in your example. What is confusing is the way that JavaScript hoisting works.
If you want to avoid hoisting use let myFn = function (...) { ... }
.
Here's a line by line, as I understand it:
// `test` defined with func declaration, hoisted to top
function test() {
return 'foo';
}
console.log(test);
console.log(test());
// `test` overwritten with function expression, hoisting has already occurred,
// `test` identifier will have this value for remainder of script
test = function() {
return 'bar';
}
console.log(test);
console.log(test());
// `test` overwritten with new func declaration, hoisted to top, but after first declaration
function test(a, b) {
return 'baz';
}
console.log(test);
console.log(test());
console.log(test(true));
console.log(test(1, 2));