Fork me on GitHub

JSLint Error Explanations

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

Function statements are not invocable. Wrap the whole function invocation in parens

When do I get this error?

JSLint will throw the "Function statements are not invocable. Wrap the whole function invocation in parens" error when it encounters a function declaration followed by a pair of invoking parentheses. In the following example we declare a function example and then attempt to immediately invoke it:

Why do I get this error?

This error is raised to highlight a JavaScript syntax error. Your code will not run if you do not fix this error.

The ECMAScript 5 specification states (section §11.2.3) that only function expressions can be invoked:

CallExpression : MemberExpression Arguments
MemberExpression : FunctionExpression

Since our example above is a function declaration (which JSLint likes to call a function statement - that can be a bit confusing, and I'll explain why shortly) it cannot be part of a call expression (since it's not a function expression as the grammar quoted above requires).

The second part of the error message tells you how to fix it. By turning the function declaration into an expression we ensure that it can be part of a call expression and can therefore be immediately invoked. To do so, we simply need to wrap the declaration, and the invoking parentheses, in another pair of parentheses:

This works because we've added a new construct, the grouping operator (ES5 §11.1.6). The specification defines the grammar for the grouping operator as follows:

PrimaryExpression : ( Expression )

So in this case, our function is actually treated as a function expression, which can be part of a call expression, and can therefore be immediately invoked.

Confusion over function declarations and statements

The terminology JSLint chooses to use for this error message can be a bit misleading. The ECMAScript specification, and the majority of other sources, will refer to a function declaration. JSLint, however, calls it a function statement. There is nothing really wrong with that, but Mozilla implemented an extension to ECMAScript in the Gecko engine called function statements. They are non-standard and it's unlikely you will come across one, so I won't go into detail, but just bear it in mind that when JSLint talks about function statements, it's talking about function declarations.

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