What does a comma do in JavaScript expressions?

  1. Home
  2. javascript
  3. What does a comma do in JavaScript expressions?

If I use:

1.09 * 1; // returns "1.09"

But if I use:

1,09 * 1; // returns "9"

I know that 1,09 isn’t a number.

What does the comma do in the last piece of code?

More Examples

if (0,9) alert("ok"); // alert
if (9,0) alert("ok"); // don't alert

alert(1); alert(2); alert(3); // 3 alerts
alert(1), alert(2), alert(3); // 3 alerts too

alert("2",
    foo = function (param) {
        alert(param)
    },
    foo('1')
)
foo('3'); // alerts 1, 2 and 3

First answer

The comma operator evaluates both of
its operands (from left to right) and
returns the value of the second
operand.

Source: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/Comma_Operator

For example, the expression 1,2,3,4,5 evaluates to 5. Obviously the comma operator is useful only for operations with side-effects.

Second answer

Have a look here – the comma stands for multiple expressions / statements. For example in your code you could use a line like this:

var a=0, b=0, c=0;

This would declare all three variables without writing:

var a=0;
var b=0;
var c=0;

Hope that helps.

Third answer


The comma operator evaluates both of
its operands (from left to right) and
returns the value of the second
operand.

https://stackoverflow.com/a/3561056/5934465

It should be like this!

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator

Reprint:https://stackoverflow.com/questions/3561043/what-does-a-comma-do-in-javascript-expressions
Spread the love

Related articles

Comments are closed.