When is the comma operator useful?

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.

Leave a Comment