views:

555

answers:

2

I have recently noticed that a lot of JavaScript files on the web starts with ; immediately following the comment section.

For example, this jQuery plugin's code starts with

/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008                                      
 .... skipping several lines for brevity...
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
;(function( $ ){

Why does the file needs to start with ;? I see this convention on server-side JavaScript files as well.

What is an advantage and disadvantage of doing this?

+10  A: 

I believe (though I am not certain, so please don't pounce on me) that this would ensure any prior statement from a different file is closed. In the worst case, this would be an empty statement, but in the best case it could avoid trying to track down an error in this file when the unfinished statement actually came from above.

Jerry Bullard
I am not 100% sure but I am with you on this one, Jerry.
o.k.w
+52  A: 

I would say since scripts are often concatenated and minified/compressed/sent together there's a chance the last guy had something like:

return {
   'var':'value'
}

at the end of the last script without a ; on the end. If you have a ; at the start on yours, it's safe, example:

return {
   'var':'value'
}
;(function( $ ){ //Safe (still, screw you, last guy!)


return {
   'var':'value'
}
(function( $ ){ //Oh crap, closure open, kaboom!


return {
   'var':'value'
};
;(function( $ ){ //Extra ;, still safe, no harm
Nick Craver
+1 for providing good examples.
Jerry Bullard
@downvoter - Always helps to say what you think is inaccurate, otherwise it doesn't help anyone who finds this.
Nick Craver
Thanks a lot for giving me good examples.
TK