The Comma Operator

The rarest operator -- it evaluates left to right and returns the last value.

Syntax(expr1, expr2, ..., exprN) // yields exprN

The comma operator evaluates each expression left to right and yields the last one. It is easy to miss because the same character separates arguments and array items, where it is not the operator.

let x = (1 + 1, 3 * 3);  // x is 9; the 2 is computed then discarded

The one place it earns its keep

Advancing multiple counters in a for loop header, where only a single expression is allowed per slot.

for (let i = 0, j = 10; i < j; i++, j--) { }

Why you rarely write it elsewhere

Outside loop headers it hides work and confuses readers. Most style guides ban it, and the linter default flags it. Knowing it exists mainly helps you read terse code, not write it.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Use the comma operator in a for-loop initialiser to declare and initialise two independent counters.
  • Understand minified code that chains expressions with commas to reduce byte count.
  • Write a concise arrow function that performs a side effect and returns a value in one expression.

More examples

Comma in for-loop header

Uses the comma operator in the init and update parts to manage two counters simultaneously.

Example · js
for (let i = 0, j = 10; i < j; i++, j--) {
  console.log(i, j);
}

Comma evaluates left then returns right

The comma operator evaluates each expression left to right and returns the rightmost value.

Example · js
let x = (1, 2, 3);
console.log(x); // 3 – only rightmost value is kept

Comma in minified side-effect arrow

Uses a comma expression inside an arrow function to perform a side effect and still return a value.

Example · js
const log = (msg) => (console.log(msg), msg.toUpperCase());
console.log(log("hello")); // logs "hello", returns "HELLO"

Discussion

  • Be the first to comment on this lesson.
The Comma Operator — JavaScript | SoundsCode