0

Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
What does this javascript syntax mean?
What does this “(function(){});”, a function inside brackets, mean in javascript?

In the below code the anonymous function is being executed.

var a= 1;
var b =2;           
(function() {  
    var b = 3;  
    a += b;  
})();  
document.write(a + " "+ b);

1) What does putting parenthesis around the function definition do?

2) What does putting () after the closing parenthesis do?

Community
  • 1
  • 1
user784637
  • 15,392
  • 32
  • 93
  • 156
  • Read this: http://stackoverflow.com/questions/593509/javascript-syntax-function-calls-and-using-parenthesis hope this helps :) – Oscar Jara Jan 31 '12 at 08:29

4 Answers4

2

Putting the () around the function() { ... } makes it an expression vs. a statement. Because it's an expression which produces a function value the () at the end invoke the produced function.

Consider the alternatives

function () { 
  var b = 3;
  a += b;
}();

This produces a syntax error as the () are essentially trying to invoke a statement.

(function () {
  var b = 3;
  a += b;
});

This produces a function object which is never invoked.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

Well you say it in the first line, the code creates an anonymous function then executes it with no arguments (the trailing parenthesis)

xpapad
  • 4,376
  • 1
  • 24
  • 25
  • Don't know why yours was given a down vote without any comments as your answer looks valid in my non-expert Javascript opinion. – CadentOrange Jan 31 '12 at 08:41
0

It a function executes it self,if you want to create an scope(or define local varible),because javascript has no block scope,a function is needed.

Guan Yuxin
  • 410
  • 6
  • 12
0

ok, Your first question answer is just covering the hole function.without it function will executed and the second one is an anonymous function with no arguments.

Rain
  • 141
  • 1
  • 2
  • 12