Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript passing ";" as the first parameter in a "for" statement

Tags:

javascript

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.

like image 875
Progo Avatar asked Jan 14 '14 04:01

Progo


3 Answers

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
like image 58
Tun Zarni Kyaw Avatar answered Nov 20 '22 03:11

Tun Zarni Kyaw


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.

like image 43
elclanrs Avatar answered Nov 20 '22 02:11

elclanrs


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.

like image 22
meagar Avatar answered Nov 20 '22 04:11

meagar