This is very similar to JavaScript plus sign in front of function name, but perhaps not quite a duplicate.
In that particular case, you don't need the parentheses you're referring to, but you do in some other cases.
In JavaScript, if the parser is expecting a statement or declaration and it sees the function
keyword, it assumes it's a function declaration (or in ES2015, a function statement). Those are not expressions (although in JavaScript, expressions are valid where statements/declarations are expected). Function declarations/statements don't produce a value you can immediately use in your code.
But if the parser is expecting an expression (for instance, on the right-hand side of an =
), function
starts a function expression. A function expression does produce a value (a reference to the function) you can use immediately in your code.
The reason you see ()
around function expressions is that people are used to writing them when they invoke the function immediately:
// WON'T WORK
function() { alert("foo"); }();
// Works
(function() { alert("foo"); }());
// Works
(function() { alert("foo"); })();
They do that to change the state of the parser from expecting a statement/declaration to expecting an expression, so that function
starts a function expression, and so has a resulting value, which they can then use to call the function via ()
.
You don't need to do that in your example because after the =
, the parser is already expecting an expression. But even though it's not necessary, it's commonly done, perhaps because it's really easy to read past the ()
at the end. That is, this:
var foo = function foo() {
// lots of stuff here
};
and this
var foo = function foo() {
// lots of stuff here
}();
are really easy to confuse. Adding the ()
to the latter makes them less similar:
var foo = (function foo() {
// lots of stuff here
})();
But it's not necessary, if people do that, it's habit and/or style.