The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
expr1, expr2, expr3...
Parameters
expr1
,expr2
,expr3
...- Any expressions.
Description
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for
loop.
The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.
Examples
If a
is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i
and decrement j
at once.
The following code prints the values of the diagonal elements in the array:
for (var i = 0, j = 9; i <= 9; i++, j--) console.log('a[' + i + '][' + j + '] = ' + a[i][j]);
Note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. In the following example, a
is set to the value of b = 3
(which is 3), but the c = 4
expression still evaluates and its result returned to console (i.e., 4). This is due to operator precedence and associativity.
var a, b, c; a = b = 3, c = 4; // Returns 4 in console console.log(a); // 3 (left-most) var x, y, z; x = (y = 5, z = 6); // Returns 6 in console console.log(x); // 6 (right-most)
Processing and then returning
Another example that one could make with comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:
function myFunc() { var x = 0; return (x += 1, x); // the same as return ++x; }
Specifications
Browser compatibility
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Comma operator | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 3 | Opera Full support Yes | Safari Full support Yes | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
Legend
- Full support
- Full support