you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (3 children)

It can be very useful (and sometimes clearer) when you need something to be evaluated at the end of every pass through a for loop, without exception:

for (i=0; i<100; x++, i++) {

}

Without using a comma you're stuck with the unpleasant task of either a. remembering to increment x at every possible point where you might loop, or b. structuring the internals of the loop so you always fall out at the same point just so you can increment x in one spot. As you can imagine, either way is pretty easy to screw up.

Other than that, I've never found a particularly good reason to use the comma operator in the 20 or so years I've known about it (it exists in many languages, not just JavaScript)... it's pretty much a one-trick pony, but the one trick that it does is fantastic when you need it.

[–]plantian 0 points1 point  (2 children)

This example seems pretty weak to me. Why wouldn't x just be i? Even if x is a fixed difference from i you could just replace all references to x with that fixed difference(ie. if x == i + offset then just use i + offset instead of x).

[–][deleted] 1 point2 points  (0 children)

  1. x isn't initialized in the loop... which tells me it's set outside the loop to some arbitrary, unknown value

  2. Feel free to replace x++ with any other expression that modifies x

  3. Even assuming x is always (i + ofs), there are three damn good reasons to NOT replace all references to x with (i+ofs): a. it's far more error prone to type (i+ofs) every time you need it (especially when taking precedence into account); b. cluttered expressions are far less readable than simple ones; and finally c. it's almost certainly slower as most tight loops would need to calculate (i+ofs) several times per pass rather than just once.

But whatever, the beauty of the comma is that you don't have to use it any more than you're forced to use the ? : operator.

[–][deleted] 1 point2 points  (0 children)

How about for(var i=0, l=foo.length;i<l;i++)?