Comma Operator

Summary

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

Operator
Implemented in: JavaScript 1.0
ECMA Version: ECMA-262

Syntax

expr1, expr2 

Parameters

expr1, expr2
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.

Example

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 the var statement is not the comma operator, because it doesn't exist within an expression. Rather, it is a special character in var statements to combine multiple of them into one. Practically, that comma behaves almost the same as 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]);

Document Tags and Contributors

Contributors to this page: Sheppy, pimvdb, Dklt, ethertank, Brettz9, Havvy, Mgjbot, Ptak82, Potappo, Dria, IgorKitsa
Last updated by: Havvy,