What's the purpose of starting semi colon at beginning of JavaScript? [duplicate]

The semi-colon is there in case you include this script just after some 'bad' script that doesn't properly close off its last line with a semi-colon. In this case it's possible the two scripts would be combined and result in invalid code. For example if you are merging multiple script into a single response.

The () at the end is executing the function. This is creating a closure. Private variables and methods can be declared within the scope of this function that cannot be accessed from outside the script.


This construct :

(function(){ /* something in here */ })()

Is used to create a new scope in Javascript.

More info on function scope here.

Regarding the semicolon, I never seen it before. I think it's a security for when you concatenate several scripts, since semicolons are optional in some cases at the end of the file.