1

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?

Crowdpleasr
  • 3,574
  • 4
  • 21
  • 37
  • 1
    Voting to close as duplicate. This has been [asked](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) and [answered](https://stackoverflow.com/a/23925102) already. – random_user_name Apr 30 '19 at 01:40

1 Answers1

2

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.

P Varga
  • 19,174
  • 12
  • 70
  • 108