Fork me on GitHub

JSLint Error Explanations

JSLint will hurt your feelings. It's time to make them better!

Function statements should not be placed in blocks

When do I get this error?

JSLint will throw the "Function statements should not be placed in blocks" error when it encounters a function declaration inside a block statement. In the following example we attempt to declare the example function if some condition evaluates to true:

Why do I get this error?

This error is raised to highlight code that may not work as you expect it to. Your code will run without error, but certain situations could cause unexpected behaviour.

Function declarations (or "function statements" as they are called in the JSLint error message) are hoisted to the top of the scope in which they appear, as described by Declaration Binding Instantiation (ES5 §10.5). Therefore, it is not possible to conditionally declare a function with a function statement. The above example is actually interpreted as follows:

As you can see, regardless of the result of the condition, the example function is always declared. If you were to, for example, declare it twice (once in an if block and once in the corresponding else block) you would actually end up with the second declaration overwriting the first regardless of the result of the condition.

Since assignments are not hoisted (they happen where you expect them to), if you want to declare a function conditionally, you can use a function expression, instead of a function declaration. A function expression is just an assignment:

James Allardice

This article was written by James Allardice, an enthusiastic young JavaScript developer at Global Personals (we're looking for developers so please apply). He is passionate about writing clean, maintainable JavaScript and uses JSHint every day to help achieve this.

You can follow him on Twitter, fork him on GitHub and find him on Google+.

Proceeds generated by this site are donated to help advance other open source projects

comments powered by Disqus