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

JavascriptJquery

Javascript Problem Overview


> 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.

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbenpalmerView Question on Stackoverflow
Solution 1 - JavascriptJames GauntView Answer on Stackoverflow
Solution 2 - JavascriptslaphappyView Answer on Stackoverflow