I was looking at the jQuery UI code, and I found that every file starts with a construct like this:
jQuery.ui || (function($) {
My question
why is there a semicolon before jQuery?
The semi-colon is there to ensure safe file concatenation. (libraries and library components are frequently packed into a single file)
why is the logical OR being done?
The self-invoking anonymous function on the right hand-side will only run if the left-hand-side of the statement evaluates to a falsey value. So if jQuery.ui
already exists on the page then the function will not run. It only runs when jQuery.ui
does not yet exist.
In English, that line of code says: either jQuery.ui exists, OR define this function...
E.g. if jQuery.ui is not defined, then the function will be created.
The initial semi-colon should have no effect - it just delimits the end of a code statement.
I think the logical OR is being done to allow for the file to be included (and evaluated) multiple times, and not clobber itself: If you load it again, jQuery.ui will be already defined, and it will not do anything.
The file could be included multiple times by mistake if someone has lost track of script tags.
As for the semicolon, I can only guess that this is a safeguard to make sure that the file also works if included in another file, even if the last statement there is not terminated by a semicolon.
A spurious semicolon does not do harm, a missing semicolon might.
I'm guessing the ;
is to ensure that javascript packers won't mess up the line, but that's the best I have.
The logical or is there to make sure that jQuery.ui
doesn't get declared twice. JavaScript does short circuit, so it won't evaluate the right hand side of the ||
if the left hand side evaluates to something that is truthey (thanks JP!).
Bonus syntax deciphering, that $ that's passed in to the anonymous function is the reference to jQuery. I had to scroll all the way down the page before that one clicked :-)
So, here's a broken down version of the line above
; // extra semi colon to ensure correct concatenation and minifying
jQuery.ui // check if the variable called jQuery.ui is truthey
|| // OR if jQuery.ui isn't defined
(function($) {...})(jQuery); // define and execute an anonymous function
// passing in the conflict safe jQuery
// as the parameter called $