Javascript: The Leading Semicolon – Mr. Joel Kemp

If you get a chance to look at some un-minified javascript code on Github or other, you might see a leading semicolon before the opening IIFE closure or a library or script:

;(function () {})();

Notice the first character, the semicolon? This looks pretty bizarre, but it’s used to prevent other poorly formed scripts from ruining your beautiful script. If another one of your scripts (or some random, bleeding-edge library) left out a semicolon (it happens), then the errors would get generated in *your* script at runtime. The interpreter would be like “I was looking for a semicolon, but I found your IIFE and I don’t like it. I don’t like your code.” You’d probably spend some minutes looking for a syntax error in your own code to no avail.

The stray, leading semicolon **is** syntactically valid, though strange. I’ve started using this technique in my scripts out of paranoia and it doesn’t sound like too horrible a practice – though slightly unreadable and unintuitive. I’m sure some javascripter lost a few hours of his/her life on that type of bug.

Just wanted to demystify that seemingly ill-placed character.