Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is JSHint's "function declarations should not be placed in blocks" too broad?

I understand why it's bad to put function declarations in CONDITIONAL blocks, but is there any reason to advise against placing a function declaration inside of a standalone block (other than the argument that it may cause confusion since JS isn't block-scoped):

{
   function foo() {};
}

The reason I'm doing this is to achieve code folding of arbitrary portions of code in Sublime Text.

like image 246
Hans Avatar asked Feb 13 '23 05:02

Hans


1 Answers

No, it's not "broad". It's the language grammar. The code you have above causes unspecified behavior and might work inconsistency in different engines. It incidentially works like you expect in most engines, but the ECMAScript specificiation forbids it in its grammar.

Use an expression instead:

{
   var foo = function(){}; // legal ECMAScript, unlike the declaration
}

Citing the annotated specification:

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 difference, 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. Use variables with function expressions instead.

As for sublime text, you can fold on annotated comments for example.

like image 67
Benjamin Gruenbaum Avatar answered Feb 15 '23 19:02

Benjamin Gruenbaum