3

I have this error from TS:

enter image description here

It's pretty clear why the error occurs:

function outer(){

   if (true) {
        function inner(){    // nested function declaration

       }
   }   
}

but my question is - why does TS complain about that - is there some technical reason I should avoid nested function declarations when transpiling to ES5?

Would a function expression be a better choice, and why?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 2
    Possible Duplicate: http://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements – SoEzPz Apr 19 '17 at 02:03
  • Some useful links also here: http://stackoverflow.com/questions/33359840/functions-may-be-declared-only-at-top-level-in-strict-mode – Jevgeni Apr 19 '17 at 02:40

1 Answers1

8

Would a function expression be a better choice

Yes. The following is the way to go:

function outer() {
  if (true) {
    const inner = function() { // OK
    }
  }
}

Why?

  • ES modules are in strict mode by default.
  • strict mode does not allow function declarations in blocks

Reason why it was disallowed is covered in the original JavaScript specification. Short version: The behaviour was inconsistent between implementations.

NOTE Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations. Because of these irreconcilable differences, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations. It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered. Future editions of ECMAScript may define alternative portable means for declaring functions in a Statement context.

So when strict mode came into being (ES5) it made it disallowed.

basarat
  • 261,912
  • 58
  • 460
  • 511