Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
expr1, expr2, expr3   // evaluates all three, result is expr3

Try it

JS Value of a comma expression

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS A classic use: two counters in a for loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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, 2 assigns 1 to a and then evaluates 2. Use parentheses (a = (1, 2)) when you want the last value.
  • Different from separators. In f(a, b), [a, b], { a, b } and let a = 1, b = 2 the commas belong to the surrounding grammar, so no comma operator is involved.
  • Most useful in for headers, where the initializer and update parts allow only one expression each, as in i++, j--.
  • Indirect calls. The idiom (0, obj.method)() evaluates obj.method to a plain function value, so it is called without obj as this. Compilers and bundlers emit this form; you rarely need to write it by hand.
  • Readability. Outside of for loops, 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 with return reads better.

Browser support

Supported in every JavaScript environment since the earliest versions of the language.