Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of the following JS structure? [duplicate]

Tags:

javascript

Possible Duplicate:
JavaScript: Why the anonymous function wrapper?

Sometimes I see a structure like this in JS programs:

(function() {
 // blah blah
})();

Any ideas what's this doing and what are its side-effects and benefits?

like image 805
Behrang Avatar asked Dec 09 '22 15:12

Behrang


2 Answers

It's to create a new scope (to avoid polluting the parent one). Surprisingly (to beginners familiar with C-like languages), JavaScript does not create a new scope when you use braces alone:

{
  var a = "foo";
}
// a still == "foo".

(function() {
  var b = "bar";
})();
// b doesn't exist.

However, functions always create a new scope. Thanks to JavaScript's closures, existing variables from the parent scopes are automatically brought (closed) into the anonymous function. So in cases (like in the question) where the anonymous function is used nowhere else (since it's never assigned), it basically acts like a C-style brace.

like image 187
Matthew Flaschen Avatar answered Dec 21 '22 23:12

Matthew Flaschen


Unlike many other curly-brace-delimited languages, JavaScript does not scope variables to the nearest enclosing block. Instead, var statements scope variables to the enclosing function. A common mistake among JavaScript programmers is to declare vars inside a loop or conditional with the assumption that they will go out of scope upon the end of the block.

Creating an anonymous function, and then executing it immediately (by placing the () after it) causes a new scope to be created, ensuring that variables declared within wil not interfere with other JavaScript that may be hanging around. Wrapping the entire thing in another set of parens makes it an expression, which can resolve some syntax ambiguities for maximum browser compatibility.

like image 25
friedo Avatar answered Dec 21 '22 22:12

friedo