Crowdpleasr
Crowdpleasr

Reputation: 4044

Please explain two syntaxes for IIFE

Is there any difference between: (function () {})(), and (function () {}())?

I've seen both constructs referenced, and would like to know if they represent two equivalent ways of constructing the exact same expression, or are they two different expressions/constructs altogether? If different, how are they different?

Upvotes: 1

Views: 28

Answers (1)

P Varga
P Varga

Reputation: 20239

These expressions are equivalent.
A closure is created, then called. The value of the expression is the closure's return value.

The simplest form would be function () {}(), however at the top level, where an IIFE would be used, that is a SyntaxError. Therefore either the creation of the closure, or the whole expression is parenthesized. However it would work in an expression context, for example

let a = function () {}()

Update: A third form you'll sometimes see, for example in minified JS is !function () {}(), of course the return value is different in this case.

Upvotes: 2

Related Questions