Why do many javascript libraries look like this:
(function () {
/* code goes here */
})();
It appears to define an unnamed function whic
If forces scope declaration. By putting it in a function you are making sure that the variables you create and call aren't being re-declared or you aren't accidentally calling variables which are declared elsewhere.
so.....
var variable = 5; // this is accessible to everything in the page where:
function ()
{
var variable = 7 // this is only available to code inside the function.
}
Here is a link to Douglas Crockford's site talking about scope in Javascript:
http://javascript.crockford.com/code.html
to follow up on the comment below:
JavaScript's scope is a little "broken":
function ()
{
var x = 3; // accessible in the entire function.
//for scope reasons, it's better to put var y = 8 here.....
if(x != 4)
{
var y = 8; //still accessible in the entire function.
//In other languages this wouldn't be accessible outside
//of the if statement, but in JavaScript it is.
}
}