views:

324

answers:

2

Hi,

when I code:

var a =
function()
{
    alert("44")
    return function(){alert(33)}
}()();

is this expression evaluated in the following order?

  1. define the function;
  2. pass its reference pointer to a
  3. a() is invoked
  4. return in a a new function pointer
  5. a() is invoked again

and if so why do I have a syntax error if I do:

function()
{
    alert("44")
    return function(){alert(33)}
}();

the interpreter wants a left operand first...

but this syntax works:

(
  function()
  {
    alert("44")
    return function(){alert(33)}
  };

)()

the outer parenthesis what does meaning???

Thanks

+3  A: 
  1. function() { alert("44") return function(){alert(33)} } you define the function
  2. function() { alert("44") return function(){alert(33)} }() you call that function returning anonymous function function(){alert(33)}
  3. function() { alert("44") return function(){alert(33)} }()() you call returned function, so it's actually equivalent to function(){alert(33)}()

So the whole execution is equivalent to:

alert("44"); alert(33);
vartec
+3  A: 

It's the syntax of the language. If you want to in-place execute an anonymous function, you must enclose it in parens.

JS has these edge cases where the syntax is weirder than you expect. Take for example, evaling a string that has a JSON doesn't work unless it's wrapped with parens.

// Wrong
eval("{ ... }");
// Right
eval("({ ... })");

It's the syntax of the language.

That said, I think (and this is strictly IMHO), the steps you've outlined are not accurate.

  1. Function is defined and invoked. alert("44"); happens as a result.
  2. The function returns another function which is also invoked. alert("33"); happens.
  3. The innermost function doesn't return anything, so a is effectively undefined. typeof a returns "undefined".
Rakesh Pai