4

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.

georg
  • 211,518
  • 52
  • 313
  • 390
Kirollos Nasr
  • 315
  • 1
  • 7

2 Answers2

4

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.

Dokt
  • 199
  • 6
  • Great, but why using *var* when declaring variables it doesn't work this way. – Kirollos Nasr Nov 06 '19 at 14:03
  • Hoisting for _var_ , _let_ and _const_ variables is different. I recommend reading this (https://scotch.io/tutorials/understanding-hoisting-in-javascript) – Dokt Nov 06 '19 at 14:22
  • 1
    No problem. I hope it helps – Dokt Nov 06 '19 at 14:25
  • Nice answer but plz change 2 with 1 in your second code example just it is in original question :) I lost 2 minutes till get notice that there mixed the other way around. – Proo1931 Nov 15 '19 at 16:46
1

It looks like this problem is due to javascript hoisting. For some reason from what I can tell declaring your function within block scope changes the way that it gets hoisted. Read more here: https://www.w3schools.com/js/js_hoisting.asp

Strike Eagle
  • 852
  • 5
  • 19