JSLint Messages – Do not wrap function literals in parens unless they are to be immediately invoked.

In JavaScript we can assign a function expression to a variable, like so:

var foo = function() {
    return 1;
}; //assign function expression to 'foo'

This is perfectly valid, and often useful.

It is also possible to assign a variable the return value of the function expression by invoking the function, like so:

var foo = (function() {
    return 1;
}()); //assign '1' to 'foo'

This is also valid, although less commonly useful.

These are two distinct techniques with distinct conventions, so, the following may well give rise to confusion:

var foo = (function() {
    return 1;
});//assign function expression to 'foo'

The above is equivalent to the first sample of code, and will execute in exactly the same way. JSLint encourages you to wrap invoked function expressions with parentheses. Wrapping non-invoked function expressions in the same way may be indicative of something non-intentional, or at very least be misinterpreted by a future developer.

In other words, stick to the first convention for the assignment of function expressions.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

2 thoughts on “JSLint Messages – Do not wrap function literals in parens unless they are to be immediately invoked.

  1. What about a situation like this one:

    var foo = (function(x) {
    return x + this.y;
    }).bind(this);

    The function is not being immediately invoked, and the parens serve a legitimate purpose, but JSLint still complains.

  2. Pingback: JSLint – A Guide To JSLint Messages | James Wiseman

Leave a Reply