2

I'm having a little trouble to understand how scope and hoisting for function declarations is behaving in the following example:

function alpha(){

  beta();

  if (true === true){

      function beta(){console.log('Aloha')};   
   }
}

alpha();

The above example is in Sloppy Mode, which means, function declarations have Function Scope. According to this, the scope of the function 'beta' should be the block of the function 'alpha'. Also the function declaration 'beta' should be hoisted within the 'alpha' function, nonetheless that is not the case. What am missing here?

Why hoisting is not working?

max fraguas
  • 438
  • 1
  • 6
  • 12
  • Don't know about the spec but if you just take a sec to think about it: The declaration of beta lies within a conditioned branch which will be evaluated once it's hit. But the call to beta happens before that. – m02ph3u5 Jul 27 '19 at 20:56
  • "*Sloppy Mode, which means function declarations have Function Scope*" - not exactly, no. The function-scoped variable is not initialised until the the function declaration was evaluated. – Bergi Jul 27 '19 at 20:58
  • Try thinking that you are running an undefined function `beta();` and then defining it after running it. `function beta(){console.log('Aloha')};` – weegee Jul 27 '19 at 20:59
  • @weegee that is the definition of hoisting. Function declarations are hoisted within their scopes, which allows you to call the function inside their scope before the declaration. – max fraguas Jul 27 '19 at 21:01
  • also here: https://stackoverflow.com/questions/50198459/how-js-hoisting-works-with-block-statement – Estradiaz Jul 27 '19 at 21:04

0 Answers0