As with this reference, Function declaration statement and variable declaration do NOT have block scope. So I am asking for why the code below executed this way.
//javascript es6
{
function bar() {
console.log("1");
}
}
function bar() {
console.log("2");
}
bar(); //prints "1" not "2"
this.bar() //also prints "1" not "2"
what I know is that the code above should consider the two functions in the global scope, but it seems like function declaration is affected by the block scope.
Basically, function declarations run before the code is executed. Let me try to make it clearer.
Let's rename the functions to this first so I can better explain how it works:
{
function bar() {
console.log("1");
}
}
function foo() {
console.log("2");
}
What your compiler does is it scans through your js file and sees that there is one function declaration which is the foo function (ignoring the one inside the brackets). Then it runs the js file as it normally would, goes inside your brackets and sees that there is another function declaration (the bar() function) which is declared after the foo() function.
So basically, this is the result you would get :
bar() // returns "2"
{
function bar() {
console.log("1")
}
}
bar() // returns "1"
function bar() {
console.log("2")
}
bar() // returns "1"
I hope it makes sense.
For more information, try looking for function expression vs function declaration and also, see how the javascript compiler works, this will give you a better understanding of how hoisting works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With