The (,) operator is cause two expressions to be executed sequentially.
Syntax
expression1, expression2
The , operator syntax has these parts:
Part |
Description |
expression1 |
Any expression. |
expression2 |
Any expression. |
Example
The , operator causes the expressions on either side of it to be executed in left-to-right order, and obtains the value of the expression on the right. The , operator is commonly used when naming variables (see example below), in the increment expression of a for loop (see example below), in function calls, arrays and object declarations.
function a() { var k=0, i, j=0; for (i = 0; i < 10; i++, j++) { k = i + j; document.write(k); } } a();
|
To run the code above, paste it into JavaScript Editor, and click the Execute button.
The for statement only allows a single expression to be executed at the end of every pass through a loop. The , operator is used to allow multiple expressions to be treated as a single expression, thereby getting around the restriction.
The example below shows how expressions are evaluated in the left-to-right order: first, n*=2 is evaluated (5*2=10), then n+=2 is evaluated (10+2=12), and the value of the rightmost argument is returned (12).
function commaDemo(n)
{
return(n *= 2, n += 2);
}
alert (commaDemo(5));
|
To run the code above, paste it into JavaScript Editor, and click the Execute button.
See also: for Statement, Operator Behavior, Operator Precedence, Operator Summary |