The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
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.
Examples
If a
is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to increment two variables at once. Note that the comma in assignments such as the var
statement are not comma operators, because they don't exist within an expression. Rather, it is a special character in such statements to combine multiple of them into one. Practically, that comma behaves similarly to the comma operator, though. The code prints the values of the diagonal elements in the array:
for (var i = 0, j = 9; i <= 9; i++, j--) document.writeln("a[" + i + "][" + j + "] = " + a[i][j]);
However, the commas joining assignments returns the left-most assignment instead of the right-most operand as does the comma operator.
// Note that the following creates 'b' and 'c' (and 'y' and 'z') as globals and is disallowed in strict mode. var a = b = 3, c = 4; console.log(a); // 3 (left-most) var x = (y = 5, z = 6); console.log(x); // 6 (right-most)
And, naturally, the comma operator is different from the comma within arrays, objects, and function arguments and parameters.
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
Specification | Status | Comment |
---|---|---|
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}} | {{Spec2('ESDraft')}} | |
{{SpecName('ES6', '#sec-comma-operator', 'Comma operator')}} | {{Spec2('ES6')}} | |
{{SpecName('ES5.1', '#sec-11.14', 'Comma operator')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES1', '#sec-11.14', 'Comma operator')}} | {{Spec2('ES1')}} | Initial definition |
Browser compatibility
{{CompatibilityTable}}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | 3.0 | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |