Why you should care
While most script engines support Function Declarations within blocks it is not part of ECMAScript (see ECMA-262, clause 13 and 14). Worse implementations are inconsistent with each other and with future EcmaScript proposals. ECMAScript only allows for Function Declarations in the root statement list of a script or function. Instead use a variable initialized with a Function Expression to define a function within a block.
How we detect
This Code Insight counts one occurrence each time a function is declared in a block:
Bad Code
if (x) { function foo() {} }
Good CodeÂ
function bar() { function inner() {return i;} if (x) { var foo = function() {}; } }
References
https://stackoverflow.com/questions/15663098/function-declarations-should-not-be-placed-in-blocks
https://rules.sonarsource.com/javascript/RSPEC-1530
https://rules.sonarsource.com/javascript/RSPEC-1530
About CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.