The comma operator separates each of its operands and evaluates all of them from left to right. It returns the value of the last operand.
Table of Contents
Examples of Comma Operator
In this example, (x++, y++, x+y)
, all three expressions are evaluated. The value last expression x+y
is returned and assigned to x. Hence x becomes 13.
1 2 3 4 5 6 7 8 9 | let x = 1; let y = 10; x = (x++, y++, x+y); //Comma Operator console.log(x) //13 |
1 2 3 4 5 6 | let x = 1; x = (2,4,5); console.log(x) //5 |
Comma operator has the lowest priority
Comma has the lowest Operator precedence of all Typescript operators. Hence in the following statement x=x++
is evaluated as the assignment operator has a higher priority or Operator Precedence. Hence x
gets the value 1
1 2 3 4 5 6 7 8 9 | let x = 1; let y = 10; x = x++, y++, x+y; console.log(x) //1 |
Hence use the parentheses to ensure that the expression is evaluates correctly.
Comma separators vs Comma operators
We use Commas everywhere. most of the time they are separators.
For Example
variable declarations: var rate = 0, amount = 0, qty = 0;
array literals const vehicles = ['car','bus','train','jeep'];
Using comma operator
We can use the comma operator wherever Typescript expects an expression.
In a arrow function or lambda expression
1 2 3 4 5 6 7 8 9 10 | const vehicles = [ 'car', 'bus', 'train', 'jeep' ]; console.log(vehicles.map(e => (console.log(e), e.length))); |
Using in For loop
We can use it in any of the arguments of the For loop to execute multiple expressions. For example, we are initializing j
variable ( j = 10,i = 0
) and also doing some calculation (j=j+i, i++
).
1 2 3 4 5 6 7 8 9 | let i=0, j=0 for (j = 10,i = 0; i < 5; j=j+i, i++) { console.log(i) console.log(j) } |
As a argument to function
We need to add parentheses here, otherwise it is treated as separator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | let x=100 let y=100 console.log(addNum(x,y)) //200 //Using Comma to add expressions console.log(addNum((x++,x+=y,x),(y++,y))) // 302 function addNum(a:number,b:number) { return a+b; } |
Reference
Read More
- Complete Typescript Tutorial
- Typescript Operators
- Arithmetic Operators
- Unary plus / Unary minus Operators
- Increment/Decrement Operators
- Comparison / Relational Operators
- Equality Operator / Strict Equality Operators
- Ternary Conditional Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Nullish coalescing operator
- Comma Operator in Typescript
- Operator Precedence