views:

135

answers:

2

In several JavaScript libraries I saw this notation at the very beginning:

/**
 * Library XYZ
 */
;(function () {
  // ... and so on

While I'm perfectly comfortable with the "immediately executed function" syntax

(function(){...})()

I was wondering what the leading semicolon is for. All I could come up with is, that it is an insurance. That is, if the library is embedded in other, buggy code, it serves as an "the last statement ends here at the latest" kind of speed bump.

Has it got any other functionality?

+12  A: 

It allows you to safely concatenate several JS files into one, to serve it quicker as one HTTP request.

porneL
But it would not be necessary, if all files would be coded up correctly, would it?
Boldewyn
No: In your example, you'd get `(function(){...})()(function(){...})()`.
Aaron Digulla
That I meant with 'coded up correctly', that every library ends with the correct amount of trailing semicolons...
Boldewyn
Yeah Boldewyn, but that’s simply not the case.
Mathias Bynens
+2  A: 

Its good when you minify js codes. Prevent from unexpected syntax errors.

S.Mark
Like what? Has the semicolon any significance for the following code or is it just for hypothetical buggy code merged in front of the actual library?
Boldewyn
In, that codes alone, no special meaning, but when that code is is in the middle of others codes and when you minify it to single line, there can be unexpected errors, like (1) semicolon is missing in previous lines, (1) previous one is also functions so it will be ()()()(), when get error, hard to debug, we cant say it buggy, because before minify its running fine.
S.Mark