Why TS complains with function declarations inside function body
Asked Answered
S

1

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?

Shin answered 19/4, 2017 at 1:23 Comment(2)
Possible Duplicate: #10069704Dost
Some useful links also here: #33360340Yes
A
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.

Airlift answered 19/4, 2017 at 5:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.