The Comma Operator
The rarest operator -- it evaluates left to right and returns the last value.
(expr1, expr2, ..., exprN) // yields exprNThe 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 discardedThe 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
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.
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.
let x = (1, 2, 3);
console.log(x); // 3 – only rightmost value is keptComma in minified side-effect arrow
Uses a comma expression inside an arrow function to perform a side effect and still return a value.
const log = (msg) => (console.log(msg), msg.toUpperCase());
console.log(log("hello")); // logs "hello", returns "HELLO"
Discussion