Why Self-Executing Anonymous works?

49 views Asked by At

I know about Self-Executing Anonymous. And usually we create them as

(function(){ return 1;})()

the reason - parser feature which didn't run if we use

function(){ return 1}()

But today I found that next code works too ( check brackets order )

(function(){ return 1;}())

function(){ return 1; }() still give me SyntaxError, as it should

Please explain why? Thx for reference to get more details

P.S. the question is about (function(){ return 1;}()) variant!

2

There are 2 answers

4
guest271314 On BEST ANSWER
(function() {})()

and

(function() {}())

are equivalent.

To call second example you can include + operator before function

+function(){ return 1 }()

See Immediately-Invoked Function Expression (IIFE)

0
Jeremy J Starcher On

The phrase IIFE is a better term for these functions .. Immediately Invoked Function Expressions.

As for why they are the same: The outer parens () simply make an expression and the () together do the invocation.

(function(){ return 1;})()
is the same as:
(function(){ return 1;}())


(function(){ return 1;})()
becomes
(functionexpression)()
becomes
functionexpression()

and

(function(){ return 1;}())
becomes
(functionExpression())
becomes   
functionExpression()

for the same reason that

(3)+2 is the same as ((3)+2).

EDIT

function(){ return 1; }()

Does NOT work because a function statement is different from a function expression. Function statements cannot be immediately invoked.