Why do many javascript libraries look like this:
(function () {
/* code goes here */
})();
It appears to define an unnamed function which is immediately called. Why go through this effort?
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.
This is standard way to do namespacing in JavaScript. If you just declare
it will be global and might conflict with other libraries, that use the same variable.
However, if you do
it is now local variable for anonymous function and is not visible outside of the scope of that function. You still can expose accessible API by not stating
varin front of variable, that way it will be global but now you have a choice.