When is the comma operator useful?

gdoron is supporting Monica picture gdoron is supporting Monica · Mar 6, 2012 · Viewed 31.4k times · Source

I read this question about the "comma operator" in expressions (,) and the MDN docs about it, but I can't think of a scenario where it is useful.

So, when is the comma operator useful?

Answer

pimvdb picture pimvdb · Mar 6, 2012

The following is probably not very useful as you don't write it yourself, but a minifier can shrink code using the comma operator. For example:

if(x){foo();return bar()}else{return 1}

would become:

return x?(foo(),bar()):1

The ? : operator can be used now, since the comma operator (to a certain extent) allows for two statements to be written as one statement.

This is useful in that it allows for some neat compression (39 -> 24 bytes here).


I'd like to stress the fact that the comma in var a, b is not the comma operator because it doesn't exist within an expression. The comma has a special meaning in var statements. a, b in an expression would be referring to the two variables and evaluate to b, which is not the case for var a, b.