0

I am studying javascript hoisting from Scope & Closures book one of You Don't Know Js books series, I understand how hoisting works but when it comes to this example it behaves in different way.

foo(); // "b"

var a = true;
if (a) {
   function foo() { console.log( "a" ); }
}
else {
   function foo() { console.log( "b" ); }
}

The book mentioned the Output supposed to be "b" due to the functions hoisting and overriding, But the result in my browser is this error.

Uncaught TypeError: foo is not a function
    at <anonymous>:1:1

So what happened in this case to throw TypeError ?

MrCoder
  • 163
  • 1
  • 2
  • 10
  • 2
    [right below this example](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch4.md#review-tldr) in the You Don't Know JS book, he says "However, it's important to note that this behavior is not reliable and is subject to change in future versions of JavaScript, so it's probably best to avoid declaring functions in blocks." – LShapz Jul 31 '18 at 21:14
  • 1
    I don't believe this was actually a duplicate. You're getting a TypeError because you tried to call foo() before you declared it. – mrshl Jul 31 '18 at 21:20
  • 3
    @unmarshalled I'm pretty sure it is a duplicate, you should learn about hoisting. Check e.g. this: `foo(); function foo() { console.log("works!"); }`. – ASDFGerte Jul 31 '18 at 21:21
  • @ASDFGerte It appears you're correct! Thanks for pointing out something I don't know. – mrshl Jul 31 '18 at 22:19

0 Answers0