Comma operator in FOR loop, how does that work?

3.6k views Asked by At

Can anyone please explain the comma operator in FOR statement?

function funct_1(c){
    for (var a = x, e = y; 0 < c; ){ 
         var p = c/2;
         var c = c/10; // wtf, it is already defined as function argument!!
    }
}

Also, the last statement like "a++" seems to be missing. I have never seen anything like this. what does that mean?

3

There are 3 answers

7
AudioBubble On BEST ANSWER

The comma just adds separation for multiple declarations. In other words, your for loop is setting a equal to x, as well as e equal to y.

As for the lack of the increment statement, the fact that it is missing just means that the for loop won't explicitly increment any variable.

1
Richard J. Ross III On

The comma operator in C, C++, and JavaScript (maybe C#) works like this:

comma_operator(statement_1, statement_2) {
     execute statement_1
     return statement_2
}

So, in your loop, it initializes two integer values, a and e, which are set to x and y, respectively. There is no increment because the loop is comparing against c, which is probably set somewhere inside the loop.

2
David Clarke On

The comma just allows you to initialise more than one variable at the start of the loop. And the missing increment operator means that there must be some script inside the loop that will eventually satisfy the termination condition, otherwise the loop would never complete.