1

I tried calling

function(v){alert(""+v);}(4);

But warning came out

function statement requires a name


When I called using name

function fname(v){alert(""+v);}(4);

Nothing happened

But when I called using brackets,

(function(v){alert(""+v);})(4);
and
(function fname(v){alert(""+v);})(4);

Both showed alert on screen. Why did this all happened?

Rahul Jain
  • 327
  • 2
  • 17
  • 1
    Although the question title talks about a plus sign rather than parentheses, the answers there answer this question (which is the dupe test on SO). Hope that helps. – T.J. Crowder Jan 23 '16 at 14:12
  • [Why are parentheses require around JavaScript IIFE?](https://stackoverflow.com/questions/31910216/why-are-parentheses-require-around-javascript-iife) – Andreas Jan 23 '16 at 14:13
  • @T.J.Crowder, Both function expression and function declaration starts with function keyword. Why would parser expect it to be declaration? – Rahul Jain Jan 23 '16 at 14:15
  • No, expressions here start with a `(` or with a `+` or a `!`, etc. – MinusFour Jan 23 '16 at 14:17
  • 1
    @RahulJain: Because it's where a statement is expected rather than an expression, and they had to make a decision about what `function` meant there, and that's what they decided. E.g., it's arbitrary. Even though JavaScript has *ExpressionStatement* (you can use an expression as a statement), you can't use a *FunctionExpression* as a statement, just because it's ambiguous. So (as the linked question's answers say), we have to do something to put the parser in a state where it's expecting *only* an expression, not a statement. `(` does that, as does `+`, ... – T.J. Crowder Jan 23 '16 at 14:18
  • @MinusFour: Rahul's speaking of the general case: A function expression does indeed start with `function`, just like a function declaration does. So it's context that tells the parser which production it should treat it as. – T.J. Crowder Jan 23 '16 at 14:19
  • Should I delete this question as it is marked duplicate? – Rahul Jain Mar 10 '16 at 16:59

0 Answers0