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

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

Possible Duplicate:
What does the leading semicolon in JavaScript libraries do?

I have noticed a lot of jQuery plugins start with
;(function(){ /* something in here */ })();

I just wondered what the beginning semi-colon was for, as well as the empty parentheses at the end.

Solutions/Answers:

Solution 1:

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.

Solution 2:

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.