0

There is a piece of code :

(function aaa(){alert("555")})()

and this :

(function aaa(){alert("555")}())

What is the difference?

Ilnyr
  • 101
  • 1

1 Answers1

0

If you put the first one together twice, it only runs the first one before producing a TypeError:

(function aaa(){alert("555")})()(function aaa(){alert("555")})()

If you put the second one together twice, it runs both of them before producing a TypeError:

(function aaa(){alert("555")}())(function aaa(){alert("555")}())

In short, they're two different style choices for scoping code to avoid cluttering the global namespace, but the second one in my experience tends to be favored more since it's less prone to erroring when multiple scopes are concatenated together. It's best to always begin the scope with a semicolon to ensure that it executes when concatenated like so:

;(function aaa(){alert("555")}());(function aaa(){alert("555")}())
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • Correction: type errors, not syntax errors. They're type errors because you're attempting to call something that isn't a function as a function. – Mike Cluck Jul 07 '16 at 20:37
  • 1
    You're right. I said syntax error, I was thinking logic error in my head. Thank you for the correction. – Patrick Roberts Jul 07 '16 at 20:41