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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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.