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 is: why is there a semicolon before jQuery
, and why is the logical OR being done?
These days, most cross-browser JavaScript problems are seen: When poor-quality browser-sniffing code, feature-detection code, and vendor prefix usage block browsers from running code they could otherwise use just fine. When developers make use of new/nascent JavaScript features, modern Web APIs, etc.)
Usually when you encounter $() , that means the developer is using a javascript library, such as jQuery. The $ symbol is the namespace for those libraries. All the functions they define begin with $. , such as $. get() .
programming puzzle by using the programming language. keywords/reserved words cannot be used when declaring variables in js E.g;var,let,this,const,import etc....
$ is pretty commonly used as a selector function in JS. In jQuery the $ function does much more than select things though. You can pass it a selector to get a collection of matching elements from the DOM. You can pass it a function to run when the document is ready (similar to body.
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.
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 $
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With