Using the following code, which is not ES6, and it is not in "strict mode", I expected the result to be "b" because the second declaration of foo should overwrite the first. But the result is "a"!
{
function foo() {
console.log('a');
}
}
function foo() {
console.log('b');
}
foo();
You would surround this sample code with extra curly braces, then the result would be the expected "b".
{
{
function foo() {
console.log('a');
}
}
function foo() {
console.log('b');
}
foo();
}
For an additional illustration, please consider the following additional example:
foo('before declaration');
{
function foo(s) {
console.log('from inside block: ' + s);
}
}
function foo(s) {
console.log('from outside block :' + s);
}
foo('after declaration');
In my decision, the correct result should be
// from outside block :before declaration
// from outside block :after declaration
I cannot find my mistake here.
If I again enclose the complete last example inside curly braces, for example
{
foo('before declaration');
{
function foo(s) {
console.log('from inside block: ' + s);
}
}
function foo(s) {
console.log('from outside block :' + s);
}
foo('after declaration');
}
I will get the expected result.
source
share