158

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?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Boldewyn
  • 75,918
  • 43
  • 139
  • 205

6 Answers6

141

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Kornel
  • 91,239
  • 30
  • 200
  • 278
  • 16
    But it would not be necessary, if all files would be coded up correctly, would it? – Boldewyn Dec 09 '09 at 13:46
  • 8
    No: In your example, you'd get `(function(){...})()(function(){...})()`. – Aaron Digulla Dec 09 '09 at 13:52
  • 8
    That I meant with 'coded up correctly', that every library ends with the correct amount of trailing semicolons... – Boldewyn Dec 09 '09 at 14:05
  • 6
    Yeah Boldewyn, but that’s simply not the case. – Mathias Bynens Dec 23 '09 at 10:46
  • that's why you can debug in IE7, where it screams at you if you're missing a semicolon with the debug tools open. – ps2goat Aug 08 '14 at 05:23
  • 13
    Two badly coded files will not be fit just by the fact that a third file contains this dirty fix. Why can not the concatenator add extra semicolons between files in the result? – Dávid Horváth Dec 03 '15 at 12:06
  • 1
    Because you don't know what concatenator(s) will ultimately be used you have to assume it won't add the semicolon. – Henry Jul 13 '17 at 02:00
  • 1
    If it were a good project, you'd have enough control to go in and manually fix all the files. If it's the case that you don't have enough control it should be written as: `;// dirty hack due to dumb concatenating process` new-line. In no way should it be construed as "best-practice". And if your dumb concatenation isn't optimizing the JS and taking out the comments? Yeah; regular users aren't reading your JS comments. – dlamblin Aug 21 '18 at 06:40
  • @Boldewyn setting aside how files end, if you have in the middle of your own script two back-to-back IIFEs and neglect to add the leading semicolon on the 2nd one it will throw an error. You mentioned "coded up correctly", but relying on ASI and omitting semicolons whenever possible is a valid way to code which more and more developers are moving to. But everyone who goes "no semicolons" in their code always use a leading semicolon on IIFEs. – jinglesthula Mar 25 '19 at 16:09
30

The best answer was actually given in the question, so I will just write that down here for clarity:

The leading ; in front of immediately-invoked function expressions is there to prevent errors when appending the file during concatenation to a file containing an expression not properly terminated with a ;.

Best practice is to terminate your expressions with semicolons, but also use the leading semicolon as a safeguard.

holographic-principle
  • 19,590
  • 10
  • 44
  • 62
  • Why also terminate your expressions with semicolons, if you're using defensive semicolons? Either you take the chance of relying on semicolons being there at the end of every line, or you use defensive semicolons. Doing both makes people incorrectly conclude that there is a reason to do both. The advice to use defensive semicolons is good; the advice to also replace every instance of `"\n"` with `";\n"` makes no sense. – Vladimir Kornea Apr 01 '15 at 12:29
  • 4
    @VladimirKornea: because you're not always using only your own libraries :) – jvenema Feb 15 '16 at 22:02
  • 6
    Because you can't rely on someone else's code following your conventions. Code defensively and then you don't have to. – jvenema Feb 16 '16 at 22:40
  • 1
    @VladimirKornea You can think of that as defensive as well, if you want -- it defends against someone else's code that doesn't always begin with defensive semicolons. – Nathan Hinchey Mar 20 '17 at 01:08
26

In general, if a statement begins with (, [, /, +, or -, there is a chance that it could be interpreted as a continuation of the statement before. Statements beginning with /, +, and - are quite rare in practice, but statements beginning with ( and [ are not uncommon at all, at least in some styles of JavaScript programming. Some programmers like to put a defensive semicolon at the beginning of any such statement so that it will continue to work correctly even if the statement before it is modified and a previously terminating semicolon removed:

var x = 0 // Semicolon omitted here
;[x,x+1,x+2].forEach(console.log) // Defensive ; keeps this statement separate

Source:

JavaScript: The Definitive Guide, 6th edition

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Faraz Kelhini
  • 3,717
  • 30
  • 38
9

This is referred to as a leading semicolon.

Its main purpose is to protect itself from preceding code that was improperly closed, which can cause problems. A semicolon will prevent this from happening. If the preceding code was improperly closed then our semicolon will correct this. If it was properly closed then our semicolon will be harmless and there will be no side effects.

Daniel Baird
  • 2,129
  • 1
  • 16
  • 23
bvmCoder
  • 1,083
  • 9
  • 7
7

A one-line answer is to safely concatenate multiple JavaScript files. Using a semicolon does not raise an issue.

Suppose you have multiple functions:

IIFE 1

(function(){
  // The rest of the code
})(); // Note it is an IIFE

IIFE 2

(function(){
   // The rest of the code
})(); // Note it is also an IIFE

On concatenation it may look like:

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

But if you add a semicolon before the function it will look like:

;(function(){})();(function(){})()

So by adding a ;, it takes care if any expression is not properly terminated.

Example 2

Assume you have a JavaScript file with a variable:

var someVar = "myVar"

Another JavaScript file with some function:

(function(){})()

Now on concatenation it will look like

var someVar = "myVar"(function(){})() // It may give rise to an error

With a semi-colon, it will look like:

var someVar = "myVar";(function(){})()
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
brk
  • 43,022
  • 4
  • 37
  • 61
4

It's good when you minify JavaScript code. It prevents unexpected syntax errors.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
YOU
  • 106,832
  • 29
  • 175
  • 207
  • 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 Dec 09 '09 at 13:50
  • 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. – YOU Dec 09 '09 at 14:18
  • 2
    But surely it's the responsibility of the minifier to handle this correctly. Are buggy minifiers the norm nowadays? – Vladimir Kornea Apr 01 '15 at 12:33