Comma Operator in JavaScript

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 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

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

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

As an argument to the function

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

Reference

  1. Expressions & Operators

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