0

What purpose does the outer parentheses serve:

(function (){}());

As I understand it I am creating an anonymous function, then calling it with the (), but what does the outer parentheses do? I've seen this in a video tutorial, but it wasn't fully explained.

Paul Here
  • 3
  • 1
  • It's a dirty hack that helps JS parser to understand that it's a function expression not a function statement. And, yes, it's completely counter-intuitive. – zerkms Feb 04 '15 at 03:36
  • 1
    I woudln't call it a "hack"; it's just JavaScripte syntax. – Pointy Feb 04 '15 at 03:37
  • This should cover it - http://stackoverflow.com/questions/1634268/explain-javascripts-encapsulated-anonymous-function-syntax – JMP Feb 04 '15 at 03:38
  • @Pointy it's a syntax approach caused by poor language design (that's what I usually call hack) – zerkms Feb 04 '15 at 03:38

2 Answers2

3

Those are the self-executing part. The first set of brackets contain the expressions to be executed, and the second set of brackets executes those expressions.

And why are those () extras?

you need to use them because when the Javascript Parser run and see the function keyword, so he will assume you are starting a a function statement and you will get some nasty syntax error,

also you need to know that function expressions and function statements are two differents things but unfortunately the syntax is almost equal, so thats why we are using those () extras, like @zerkms says its kinda a "hack"

Ethaan
  • 11,291
  • 5
  • 35
  • 45
0

Putting the outer parentheses means You are going to execute it not to define, this is to do with the JS parsing rules. You always have the option to do this nicer than this lame way. :)

Hope this helps!

Kevin Simple
  • 1,225
  • 10
  • 22