dzjustinli2 dzjustinli2 - 5 months ago 10
Javascript Question

Are the parentheses enclosing "function incrementNumber()" optional?

I'm new to JavaScript and am trying to learn JavaScript closures. I have two versions of the same code, the only difference is that version 2 has parentheses enclosing the function. I have run both versions and they seem to produce identical results. I was wondering if the parentheses enclosing "function incrementNumber()" are optional?

Version 1:

var incrementFunctionVariable = function incrementNumber(){
var clickCount = 0;
return function (){
return ++clickCount;
}
}()


Version 2: parentheses enclosing "function incrementNumber()"

var incrementFunctionVariable = (function incrementNumber(){
var clickCount = 0;
return function (){
return ++clickCount;
}
})()

<input type="button" value="click me" onclick="alert(incrementFunctionVariable())" /><br>

Answer

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.