1

I'm reading The ES6 & Beyond book, Chapter 2: Syntax for the You Don't Know JS series. He mentions how functions are block scoped in ES6, and gives this example, that I altered.

I changed the name to fooBlock and had it print something out to the console. So I expected the first calling of fooBlock to work, and the second calling of it to give an error...but instead it was able to call the function outside the block scope.

What am I not getting?

{
    fooBlock(); //prints "Here is fooBlock"

    function fooBlock(){
        console.log("Here is fooBlock");
    }
}
fooBlock(); //prints "Here is fooBlock" when I expected an error
  • 1
    I don't know the exact background on this but seems functions are hoisted up until another function, they seem to ignore block scopes. `const/var fooBlock = function fooBlock() { ... }` would work though. Interested to learn the exact rules on function hoisting +1 – Dominic Oct 09 '17 at 15:18
  • 1
    Only `let`/`const` bindings respect block scope. Function declarations act like `var`. Try `const fooBlock = function(){...}` instead. –  Oct 09 '17 at 15:20
  • @ftor and DominicTobias: No, function declarations have block scope. – Bergi Oct 09 '17 at 15:32
  • 1
    If you had used strict mode (which you always should!), it would work as expected – Bergi Oct 09 '17 at 15:32
  • @Bergi, strict mode worked, thanks! Do you think I should notify the author about telling the reader to use strict mode for this example? –  Oct 09 '17 at 15:55
  • @00Saad Sure, feel free to do that. But rather have him tell the reader to use strict mode by default for *every* example. – Bergi Oct 09 '17 at 15:57
  • @Bergi, he does mention the importance of strict mode early on and multiple times across his book. I just wonder why it was necessary in this particular case when let/const worked as expected. –  Oct 09 '17 at 16:23
  • @00Saad See the duplicate for the why :-) Basically, in sloppy mode they needed not to to break the web which abused "function statements" with function-level scope. – Bergi Oct 09 '17 at 17:54

0 Answers0