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?

7
  • 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. Commented Sep 30, 2013 at 17:53
  • possible duplicate of Explain JavaScript's encapsulated anonymous function syntax Commented Sep 30, 2013 at 17:54
  • I forget one to add some more () - check this now. Commented Sep 30, 2013 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. Commented Sep 30, 2013 at 17:55
  • It is not question how to do anonymous function or execute but why this syntax works? Commented Sep 30, 2013 at 17:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Now I am understand () is similar operator like ! both forces evaluation - thanks - this question irritate me long - it is so trivial :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.