The benefit of the comma operator is that it allows you to include a sub-expression for its side-effects only. In languages without a comma operator, there are often ways around this ─ suppose f
is an expression you want to evaluate just for its side-effects, and then g
is the expression whose value you actually want:
- In languages with list or tuple literals, you can write
[f, g][1]
.
- In languages with logical operators permitting it, you can write
(f || true) && g
, or (more cryptically) f && g
or f || g
when f
's truthiness is constant.
- In languages with
let
-in
expressions, you can write let _ = f in g
.
- In most cases, you can define a function like
comma(f, g)
which just returns g
.
So the comma operator does not really add expressiveness to the language, it just allows you to write this kind of expression explicitly instead of using an idiom. On the other hand, this kind of expression is rarely needed in real code written by humans; personally, I only use JavaScript's comma operator in Code Golf challenges or to simulate let
-in
expressions like (x=f, g)
when compiling to JavaScript.
Also, including the comma operator like this may mean less syntax space is available for other things. For example, in Python, (f, g)
or f, g
are expressions which create a tuple, so they can't also mean something else.
The comma operator would also be almost entirely superfluous in languages where expressions cannot have side-effects, such as pure functional languages ─ the first operand would only matter if it was eagerly evaluated but diverged. (Haskell's seq
behaves like this, and is considered harmful by some.)
(12, 42)
because otherwise you're trying to declare a variable named42
. $\endgroup$