2

I found such two code and not understand the difference between them if any exists.

Can you explain me what is difference between code preventing global scope polution.

First:

(function() {
var x = 1;
// thousand of lines here
}(window));

Second:

(function() {
var x = 1; 
// thousand of lines here
})(window);

Question can be trivial but I am not understand difference what is doing (); - can you explain it?

Chameleon
  • 8,304
  • 13
  • 51
  • 101
  • 3
    If that's really exactly what the code looks like, then the difference is that the first one is not a syntax error, but the second one is. – Pointy Sep 30 '13 at 17:53
  • possible duplicate of [Explain JavaScript's encapsulated anonymous function syntax](http://stackoverflow.com/questions/1634268/explain-javascripts-encapsulated-anonymous-function-syntax) – Pointy Sep 30 '13 at 17:54
  • I forget one to add some more () - check this now. – Chameleon Sep 30 '13 at 17:55
  • This is a duplicate (sometimes it can be hard to find them if you don't know the right terms to search for), and the other answer is really worth reading. He put a lot of good stuff in there. – Travis J Sep 30 '13 at 17:55
  • It is not question how to do anonymous function or execute but why this syntax works? – Chameleon Sep 30 '13 at 17:57
  • @Chameleon look at CMS's answer in [this question](http://stackoverflow.com/questions/1634268/explain-javascripts-encapsulated-anonymous-function-syntax). – Pointy Sep 30 '13 at 17:58
  • @minitech answer is honey - now I am understand what I am writing thousand times :) – Chameleon Sep 30 '13 at 18:01

1 Answers1

4

When the JavaScript parser reads a function token at the start of the line, it assumes it’s a function declaration, i.e.

function hello() {
    return "world";
}

When it doesn’t see a name after that, it’s a syntax error. The parentheses make the context an expression instead of a statement/declaration, meaning that a function literal is expected.

Fun fact: you don’t need parentheses to force an expression context, of course. Unary operators will work too, e.g.

!function() {
    var x = 1;
}();

Oh, and you’ve gone and changed the question. The new answer is: they’re both exactly the same, kind of like 5 + (4 * 3) versus (5 + 4 * 3), except even less important because they’re more or less equally readable.

Ry-
  • 199,309
  • 51
  • 404
  • 420
  • Now I am understand () is similar operator like ! both forces evaluation - thanks - this question irritate me long - it is so trivial :) – Chameleon Sep 30 '13 at 18:00