Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript self-executing functions - different syntax [duplicate]

I've seen 2 versions of self executing javascript functions:

(function() { ... })()

and

(function() { ... }())

note the different placement of the function execution "()"

Is there a difference between these two?

like image 358
Chris Avatar asked May 29 '26 02:05

Chris


2 Answers

There are many ways to get the effect of what you're doing, and strictly speaking this topic has only tangential relation to the subject of closures.

The problem is this: in JavaScript, the function keyword serves two different purposes:

  1. It introduces a function declaration statement, which is kind-of like a var statement (variable declaration) but for a function;
  2. It introduces a function literal expression in the context of a larger expression.

Now the problem is that when the parser sees function at the beginning of a statement, it assumes you mean to declare a function; that is, case 1 above. When you declare a function, you cannot call it in the same statement; the function declaration statement just declares the function.

Thus, if what you want is a statement that consists only of the creation of a function and its immediate invocation, you have to put the parser in the mood to parse an expression. Putting the whole thing in parentheses is just one way of doing that.

Any "trick" that convinces the parser that what it's seeing is an expression statement will do:

var dummy = function() { ... whatever ... } ();

!function() { ... whatever ... } ();

0 + function() { ... whatever ... } ();

All of those, and countless other examples, set things up such that when the parser sees the function keyword, it does so in the middle of an expression.

If Mr. Eich had picked a different keyword for the instantiation of a function object mid-expression (like lambda for example), there'd be no problem, because you could then just say

lambda () { ... whatever ... } ();

He didn't, however.

like image 150
Pointy Avatar answered May 30 '26 15:05

Pointy


The parenthesis ensure you have an expression (which cannot starts by the function keyword), so that it may be executed.

From ECMAscript Language Specification :

Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

This works too :

(((((function() {...}))())));​
like image 34
Denys Séguret Avatar answered May 30 '26 16:05

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!