skip to content

In JavaScript, what does `return log(x), x * 2;` return, and how does the comma operator differ from the commas in `f(a, b)`?

level: middleimportance: should knowfreq 32%

answer

  1. evaluate all, keep one
  2. left to right, last one wins
  3. separator versus operator
  4. lower precedence than assignment
  5. a value, not a reference

basics

~20 s

return log(x), x * 2 calls log(x), discards its result and returns x * 2. The comma operator runs operands left to right and yields the last; commas in argument lists and declarations are only separators.

solid answer

~50 s

`return log(x), x * 2;` calls `log(x)`, throws its result away, and returns `x * 2`. The comma operator evaluates each operand left to right and produces the value of the last, so the earlier ones are only useful for their side effects. The commas in `f(a, b)`, `[1, 2]`, `{ a: 1, b: 2 }` and `const a = 1, b = 2` are syntax separators instead, so `Math.max(1, 2)` gets two arguments and `Math.max((1, 2))` gets one. The operator also has the lowest precedence of all, lower than assignment: `x = 1, 2` assigns `1`, while `x = (1, 2)` assigns `2`. Its result is a value and not a reference, so `(0, obj.method)()` calls the method without `obj` as `this`. In review I accept it in a `for` afterthought such as `i++, j--` and in small arrow functions, and elsewhere ask for separate statements.

code

javascript · 9 lines
javascript
let x;
x = 1, 2;
console.log(x); // 1

x = (1, 2);
console.log(x); // 2

console.log(Math.max((1, 2))); // 2
console.log([[1, 2], [3, 4]][0, 1]); // [ 3, 4 ]

go deeper

for a junior

Remember the one-line rule: every operand runs, left to right, and the last value is the result. Know that the commas in calls, arrays and object literals are not this operator.

for a middle

Explain why x = 1, 2 assigns 1, predict a bracketed or parenthesised comma expression, and describe why a comma expression gives back a value rather than a reference, which changes this.

for a senior

Recognise the operator while reading minified or transpiled code, including the (0, fn)() pattern, and treat return a, b in hand-written code as a likely bug rather than as style.

for a principal

There is not much to own beyond a lint default: allow the comma operator in for headers, forbid it elsewhere, and exempt generated code. It is a small rule that removes a small class of misreadings.

## What the operator does The **comma operator** joins expressions into one expression. It exists for places where the grammar allows a single expression but you want more than one thing to happen. Evaluating `a, b, c` takes three steps: 1. Evaluate `a` and discard its value. 2. Evaluate `b` and discard its value. 3. Evaluate `c` and produce its value as the result of the whole expression. ```javascript function double(x) { const log = () => console.log("logged", x); return log(), x * 2; } console.log(double(21)); // logs "logged 21", then 42 ``` Since the earlier values are thrown away, an earlier operand does something only through a **side effect**: an assignment, a call, `++`, or a getter that does something. Without one it is inert, and any remaining purpose lies in what the operator does to its last operand, as the section on references below shows. ## Separator or operator? Most commas in JavaScript are not this operator. They are punctuation in a list, and each of these places treats a comma as a boundary between items: | Where | Example | The comma is | |---|---|---| | Call arguments | `f(a, b)` | a separator | | Array literal | `[1, 2]` | a separator | | Object literal | `{ a: 1, b: 2 }` | a separator | | Parameters | `function f(a, b) {}` | a separator | | Declaration list | `const a = 1, b = 2;` | a separator | | Import and export lists | `import { a, b } from "c";` | a separator | | Bracket access | `grid[1, 2]` | the operator | | `for` afterthought | `i++, j--` | the operator | | After `return` | `return a, b;` | the operator | Parentheses turn a list position into a single expression. `Math.max(1, 2)` passes two arguments and gives `2`. `Math.max((1, 2))` passes one argument, the value `2`. `const a = (1, 2);` is legal and sets `a` to `2`, while `const a = 1, 2;` is a `SyntaxError`, because the parser wants another binding name after that comma. ## The lowest precedence of all The comma binds more loosely than assignment, and that produces most of the surprises: - `x = 1, 2` groups as `(x = 1), 2`, so `x` is `1` and the expression's value is `2`. - `x = (1, 2)` sets `x` to `2`. - `a = b = 3, c = 4` sets `a` and `b` to `3` and `c` to `4`, and the expression's value is `4`. To use a comma expression inside a larger expression, you have to parenthesise it. An arrow function with an expression body is the common case: `(x) => (log(x), x + 1)`. ## A value, not a reference A property access such as `obj.method` produces a **reference** that remembers `obj`, which is how a following call knows its `this`. Plain grouping keeps that reference, but the comma operator produces a bare value, so the connection is gone: ```javascript const counter = { label: "c1", read() { "use strict"; return this === undefined ? "no this" : this.label; }, }; console.log(counter.read()); // "c1" console.log((counter.read)()); // "c1" console.log((0, counter.read)()); // "no this" ``` You will see `(0, helper.fn)(args)` in transpiled module output. It looks pointless, yet it deliberately calls the function without `helper` as `this`, matching how a named import behaves. The same technique turns `(0, eval)(code)` into an indirect `eval`, which runs in global scope. ## Where it belongs - **A `for` loop with two counters**: `for (let i = 0, j = 9; i <= 9; i++, j--)`. The comma in the initialiser is a declaration separator, and the one in the afterthought is the operator. - **A short arrow function** that must do one small thing before returning, such as `xs.map((x) => ((sum += x), x * x))`. - **Minified output**, where a tool merges statements. You will read this while debugging, and you need not write it. ## Reading it in review - `return a, b;` written by someone expecting two return values is a bug, so ask for an array or an object. - `grid[1, 2]`, from someone used to another language's multi-dimensional syntax, reads `grid[2]`. - `if (a, b)` tests only `b`, which is more often a slip than a design. - A comma in the middle of an ordinary function body is better as two statements, and a linter can enforce that outside `for` headers.

  • Why does transpiled code call functions as `(0, mod.fn)(arg)`?
    Writing `mod.fn(arg)` would pass `mod` as `this`, which a named import never does. The comma operator yields the function as a bare value, so the call has no receiver. The `0` is an arbitrary operand with no side effect; only the last value matters.
  • Does `(obj.method)()` lose `this` the way `(0, obj.method)()` does?
    No. Grouping parentheses return the reference unchanged, so `(obj.method)()` still sees `obj` as `this`. Only an operator that produces a value breaks the link, and the comma operator does that. In strict code the comma form leaves `this` as `undefined`.
  • Why is `const a = 1, 2;` a SyntaxError while `const a = (1, 2);` is fine?
    In a declaration list a comma is a separator, so the parser expects another binding name after it and finds `2`. Parentheses open a fresh expression position, where a comma is the operator, so `(1, 2)` is one expression whose value `2` initialises `a`.

  • return a, b returns both values, like a tuple
  • return a, b returns a and never evaluates b
  • x = 1, 2 assigns 2 to x
  • The commas in a function call are comma operators
  • grid[1, 2] reads row 1, column 2 of a nested array
  • (obj.method)() and (0, obj.method)() always behave the same