Question

I stumbled over the following JavaScript:

Code:

var x="", i=0;
while (i<4, i<7, i<5, i<6)
{
  x=x + "The number is " + i + "<br>";
  i++;
}
document.write(x);

I never know that it is possible to use multiple comma-separated expression in one WHILE statement.

Result:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

What is the reason for this and what is the behavior (only the last expression is evaluated for the while-exit)?

Is the behavior standardize in all Javascript/C/Java languages?

Was it helpful?

Solution 2

This is a special operator in JavaScript which is called comma operator; so when JavaScript comes across this line

(i<4, i<7, i<5, i<6)

it will evaluate one by one all the operands in the parenthesis and will return the evaluation of the last item i.e. i < 6

It is rarely used; One occasion that I remember to have used it was for indirect call to eval.

(0, eval)(src)

But again in you example the use of it is redundant.

OTHER TIPS

Only the last result is kept in result of the comma operator, so

while (i<4, i<7, i<5, i<6)

is really equivalent to

while (i<6)

That's the reason why you don't see this more often : it's useless if your comparisons don't have side effects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top