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 | 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 JavaScript operators. Hence 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 evaluated 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 JavaScript expects an expression.
In an 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 calculations (j=j+i, i++
).
1 2 3 4 5 6 7 | let i=0, j=0 for (j = 10,i = 0; i < 5; j=j+i, i++) { console.log(i) console.log(j) } |
As an argument to the function
We need to add parentheses here, otherwise, it is treated as a 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
- JavaScript Tutorial
- JavaScript Operators
- Arithmetic Operators
- Unary plus (+) & Unary minus (-)
- Increment & Decrement Operators
- Comparison or Relational Operators
- Strict Equality & Loose Equality Checker
- Ternary Conditional Operator
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Nullish Coalescing Operator
- Comma Operator
- Operator Precedence