-1

I'm wondering why this works

(function Test() { 
    alert('x'); 
}())

but this doesn't work

function Test() { 
    alert('x'); 
}()

How does the outer parenthesis change the precedence of things and make it work?

dazedconfused
  • 1,312
  • 2
  • 19
  • 26
adamtki
  • 11
  • 2
  • Any statement that **starts with** `function` is a function *declaration*, and is not callable. If the function appears in an *expression*, it's a function expression, and is callable. Starting the statement with a paren makes it an expression. You can also do `!function Test(){ alert(x) }()`, but that's a less common hack than wrapping the whole thing in parens. – Carl Smith Nov 07 '14 at 00:31
  • Take a look at [function definitions](http://www.w3schools.com/js/js_function_definition.asp) at the **Self-Invoking Functions** part – dazedconfused Nov 07 '14 at 00:35
  • P.S. Please remove the jQuery tag. – Carl Smith Nov 07 '14 at 00:36

1 Answers1

-1

You can image the parenthesis is use for be explicit on what you do. Like when you do some operation like 3 * 2 + 4 or 3 * (2 + 4). When you do

function Test() { alert('x'); }()

The navigator just see 2 parenthesis alone whereas when you do

(function Test() { alert('x'); }())

It see you want to execute the function.