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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With