I have been studding the jQuery source code and I noticed this when examining the jQuery.fn.extend
function:
for ( ; i < length; i++ ){
code
}
Why is there a ;
at the beginning? Similarly, I have noticed a few javascript libraries beginning like so:
; (function (){ ...
Without any prior code.
Why is this? How is this syntactically correct?
Thank you.
JavaScript for
loop has three optional parameters. So, you can omit all of its three parameters.
In your code,
for( ; i < length; i++)
the first parameter is omitted. ;
is not passed as parameter. ;
is just a delimiter. The syntax of the for
loop is
for( [optional parameter 1] ; [optional parameter 2] ; [optional parameter 3] )
OR
for ([initialization] ; [condition] ; [final-expression])
So the following statements are syntactically correct
for( ; i < length; i ++ ) // first parameter is omitted
for( ; i < length; ) // first and third parameters are omitted
for( ; ; ) // all parameters are omitted
Those two snippets are unrelated.
The first one is an empty statement. A for
loop takes 3 statements; if you initialize the variable before the loop you don't need to initialize it inside, but the statement has to be there, hence the empty statement:
var i=0;
for (; i<10; i++) {}
A typical example is for(;;)
, same as while(true)
but shorter.
The second piece of code is the beginning of an IIFE(Immediately Invoked Function Expression). The semicolon at the start is to avoid concatenation errors from other JavaScript files that may be missing a semicolon, otherwise the IIFE might be interpreted as a function call, for example:
// file1.js
var f = function(){} // oops
// file2.js
(function(){})();
If the file did include the last semicolon, then you end up with an empty statement, which is OK.
The two examples are unrelated.
In the first case, a for
statement always has three components; an initialize, a condition, and an increment statement. All three are optional, so the code for( ; i < length; i++)
simply chooses not to initialize anything before looping.
The empty statement, ;
, is perfectly valid, there is nothing syntactically wrong with it.
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