With the following code, which is neither ES6, nor is it in "strict mode", I had expected an outcome of 'b' because the second declaration of foo
should overwrite the first one. But the outcome is 'a'!
{
function foo() {
console.log('a');
}
}
function foo() {
console.log('b');
}
foo(); // 'a' ? Why not 'b'?
When this code is surrounded with additional curly braces, the outcome is the expected 'b'.
{ // additional curly braces
{
function foo() {
console.log('a');
}
}
function foo() {
console.log('b');
}
foo(); // 'b' as expected!
} // end additional curly braces
For further illustration, please consider the following additional example:
foo('before declaration'); // outcome: from outside block :before declaration
{
function foo(s) {
console.log('from inside block: ' + s);
}
}
function foo(s) {
console.log('from outside block :' + s);
}
foo('after declaration'); // outcome: from inside block: after declaration
In my opinion the correct outcome should be:
// from outside block :before declaration
// from outside block :after declaration
I'm unable to spot my misconception here.
If I again enclose the complete last example inside curly brackets like so:
{
foo('before declaration'); // outcome: from outside block :before declaration
{
function foo(s) {
console.log('from inside block: ' + s);
}
}
function foo(s) {
console.log('from outside block :' + s);
}
foo('after declaration'); // outcome: from outside block: after declaration
}
I get the expected outcome.