When is the comma operator useful in JavaScript?

JavascriptWeb DevelopmentFront End Technology

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.

raja
Published on 09-Jan-2018 09:49:22
Advertisements