In the Re-Introduction to Javascript, the syntax
for (var i = 0, item; item = a[i++];)
is explained as the middle "item" being a conditional test for truthtiness/falsiness. However, I had assumed the syntax to be (start; condition test; control factor) with semi-colons between each segment. Here, the syntax is unfamiliar to me in the form (start, condition test; control factor;) with a comma in the middle and semicolon at the very end. Is it equivalent to
for (var i = 0; item; item = a[i++])
?
If so, why write it using comma and semicolon at the end?
In that expression, we have
var i = 0, item-- this declares two variables, and assigns one of them.item = a[i++]-- this performs an assignment, and tests the result of the assignmentnothing-- the increment ofiwas done as part of the condition, so nothing is needed hereA
for-loopis essentially equivalent to the following:So when we substitute from your loop, we get:
An assignment's value is the value that was assigned, so the condition is whether
a[i]was truthy. No control factor is needed becausea[i++]returns the value ofa[i]and also incrementsiat the same time.A more typical way to write this loop would be:
The author was just showing how you can combine many pieces of this.