Comma operator in Typescript

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.

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.

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

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

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++).

As a argument to function

We need to add parentheses here, otherwise it is treated as separator.

Reference

  1. Expressions & Operators

Read More

  1. Complete Typescript Tutorial
  2. Typescript Operators
  3. Arithmetic Operators
  4. Unary plus / Unary minus Operators
  5. Increment/Decrement Operators
  6. Comparison / Relational Operators
  7. Equality Operator / Strict Equality Operators
  8. Ternary Conditional Operators
  9. Logical Operators
  10. Bitwise Operators
  11. Assignment Operators
  12. Nullish coalescing operator
  13. Comma Operator in Typescript
  14. Operator Precedence

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top