JavaScript Reference ยท Operators
The comma operator
Reference for the JavaScript comma operator: evaluating several expressions left to right, using the last value, for-loop uses and how it differs from list commas.
The comma operator evaluates each of its operands from left to right and returns the value of the last one. The earlier operands are evaluated only for their side effects; their values are thrown away.
It is easy to confuse with the commas that separate arguments, array elements, object properties, parameters and declarations. Those commas are part of other syntax and are not the operator. The operator appears only where a single expression is expected and you write several expressions separated by commas, usually inside parentheses.
expr1, expr2, expr3 // evaluates all three, result is expr3
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
expression1, expression2 (a, b, c)
| Operand | Description |
|---|---|
expression1 |
Evaluated first. Its value is discarded. |
expression2 (and any further operands) |
Evaluated next, in order. The value of the final operand becomes the value of the whole expression. |
Return value: the value of the last operand.
Exceptions: none of its own. If any operand throws, evaluation stops there.
Usage notes
- It has the lowest precedence of all operators.
a = 1, 2assigns1toaand then evaluates2. Use parentheses (a = (1, 2)) when you want the last value. - Different from separators. In
f(a, b),[a, b],{ a, b }andlet a = 1, b = 2the commas belong to the surrounding grammar, so no comma operator is involved. - Most useful in
forheaders, where the initializer and update parts allow only one expression each, as ini++, j--. - Indirect calls. The idiom
(0, obj.method)()evaluatesobj.methodto a plain function value, so it is called withoutobjasthis. Compilers and bundlers emit this form; you rarely need to write it by hand. - Readability. Outside of
forloops, separate statements are almost always clearer. Linters often warn about the operator (no-sequences). - Arrow function bodies.
() => (log(), value)works but hides intent; a block body withreturnreads better.
Browser support
Supported in every JavaScript environment since the earliest versions of the language.