Multiple for-loop updates
A loop must update more than one variable after each iteration.
JS Puzzles · Const
The comma operator evaluates several expressions from left to right and returns only the last expression's value. Parentheses are often needed because comma has very low precedence.
The comma operator evaluates expressions from left to right and produces the value of the final expression. Earlier results are discarded, so those expressions are useful mainly when they cause side effects; parentheses are often required because the operator has very low precedence.
expression1, expression2, ...| Name | Type | Description |
|---|---|---|
expressions | expression list | Expressions evaluated from left to right; the final expression determines the compound expression's value. |
The value of the last expression.
let value = (console.log("first"), 2 + 3);
console.log(value); // 5
for (let i = 0, j = 3; i < j; i++, j--) {
console.log(i, j);
}The first expression runs for its side effect, while the parenthesized expression evaluates to the final value. The loop uses the operator to update two variables.
A loop must update more than one variable after each iteration.
Earlier expressions need to run while one final value is required.
It evaluates each operand from left to right, then returns the value of the last operand. Values produced by earlier operands are discarded.
Follow-up: What happens in (x++, x)? x++ runs first, then the updated value of x is returned by the second operand.
Its precedence is lower than assignment, so a = 1, 2 is grouped as (a = 1), 2. To assign the final result of the comma expression, write a = (1, 2).
Follow-up: Why does a = (1, 2) assign 2? Parentheses force the comma expression to be evaluated before assignment.
A common use is putting multiple update expressions in a for loop, such as i++, j--. The updates run left to right after each iteration.
Follow-up: What must earlier operands generally provide to be useful? They should normally have side effects, such as assignments, calls, or increment operations.
Basic operators, mathsOperator precedencefor statementParentheses