1

If we put function declaration inside for loop — its name will be hoisted, but it will contain undefined:

console.log(foo, bar); //undefined function bar() {}

for (var i = 0; i < 1; i++) {
  function foo() {}
}

function bar() {};

Why is it like that? It is told everywhere that var gets hoisted, leaving initialization in place, and that function declarations are fully hoisted. Seems like some specification quirk but it is curious why it works this way

RobG
  • 142,382
  • 31
  • 172
  • 209
Andrey
  • 1,018
  • 12
  • 21
  • 1
    Hoisting 101... – epascarello May 09 '17 at 23:43
  • @epascarello—I think it's more do to with function declarations/statements inside blocks, which has always been problematic and hence should be avoided. – RobG May 09 '17 at 23:44
  • 1
    Back compat. It shouldn't be hoisted to function scope at all in plain ES6. – Bergi May 09 '17 at 23:45
  • 1
    Also see [*Why JavaScript function declaration behave differently in chrome and safari?*](http://stackoverflow.com/questions/43135925/why-javascript-function-declaration-behave-differently-in-chrome-and-safari) This behaves differently in different browsers, there is also [*Why are function declarations handled differently in different browsers?*](http://stackoverflow.com/questions/8871974/why-are-function-declarations-handled-differently-in-different-browsers) – RobG May 09 '17 at 23:50
  • 1
    The issue is one of historical browser _incompatabilty_ rather than _compatability_. MDN suggest ["Don't do it"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#Block-level_functions_in_non-strict_code) in regards block level functions in non strict mode. Strict mode has issues as well: inside a for loop a new, different, function object is created for function _declarations_ during each iteration of the loop. – traktor May 10 '17 at 02:27

0 Answers0