Chameleon
Chameleon

Reputation: 10138

JavaScript anonymous function valid syntax preventing global scope polution?

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?

Upvotes: 2

Views: 129

Answers (1)

Ry-
Ry-

Reputation: 225054

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.

Upvotes: 4

Related Questions