Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the comma operator useful?

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?

like image 894
gdoron is supporting Monica Avatar asked Mar 06 '12 07:03

gdoron is supporting Monica


People also ask

Where is comma operator used in C?

The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.

How is comma operator useful in a for loop in C?

The comma operator will always yield the last value in the comma separated list. Basically it's a binary operator that evaluates the left hand value but discards it, then evaluates the right hand value and returns it. If you chain multiple of these they will eventually yield the last value in the chain.

What are commas used for in coding?

In the C and C++ programming languages, the comma operator (represented by the token , ) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type); there is a sequence point between these evaluations.

What is the purpose of the commas in arguments?

You use the comma operator, to separate two (ostensibly related) expressions. Later in the description: If you want to use the comma operator in a function argument, you need to put parentheses around it. That's because commas in a function argument list have a different meaning: they separate arguments.


1 Answers

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.

like image 176
pimvdb Avatar answered Sep 28 '22 12:09

pimvdb