When is the comma operator useful in JavaScript?


The comma operator in JavaScript evaluates each of its operands. It returns the value of the last operand. Add multiple expressions using the comma operator.

The following is the syntax:

expression1, expression2, ……expression

Use the comma operator to add multiple parameters in a for loop:

for (var a = 0, b = 5; a <= 5; a++, b--)

You can also use the comma operator in a return statement. Process before returning using comma:

function myFunc() {
   var a = 0;
   return (a += 1, a);
}

Above you can see the value of a will process and then it will be returned.

Updated on: 12-Sep-2019

41 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements