Is it good practice to start all JS files with a semi colon to account for any bad scripts included before it? Or don't bother?
Thanks
;(function(){ /* my script here */ })();
Is it good practice to start all JS files with a semi colon to account for any bad scripts included before it? Or don't bother?
Thanks
;(function(){ /* my script here */ })();
Do bother, more and more people leverage the power of ASI and write semicolonless JavaScript. In semicolonless JS world that's the "rule", you put a semicolon before raw expressions, like ;()
, or ;[]
or ;//
, as well as after 'use strict';
and omit them everywhere else. Raw expressions are not very common, except the typical IIFE.
Even if you write JS with semicolons, that particular one is safe and will do more good than bad.
not a good idea:
Instead, start all your scripts with "use strict";
which on some browsers will check your scripts for some error-prone practices, and interestingly I believe it will have a similar effect as the ;
for closing any outstanding statements from faulty scripts included prior.
The leading semicolon is actually pretty useful if you split and decouple a lot of code into several javascript files, which you at some point, concatenate to create a production file.
It will simply help to avoid errors in constructs like
(function() {
}())
if all your files are wrapped in constructs like this, it fill fail without any semicolon, separating them. Other than that, there isn't much value in that pattern.
I usually don't bother, but, if you want to be really safe, then do it. If you are using somebody else's library, I would probably do it, but, then again, it is your choice.