tags:

views:

214

answers:

3

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. So, what comma does in the last piece of code?


EDIT 1

Another example:

if(0,9) alert("ok"); // alert

But

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

EDIT 2

Yet Another example:

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

And

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

EDIT 3

Crazy example:

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

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.

Yuval A
They took it from C. I think it's only useful for expressions that have side effects.
Radomir Dopieralski
@Randomir - correct, thanks.
Yuval A
+2  A: 

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.

Regards, Daniel

dhh
A: 

Some more alerts to consider:

alert((0, 9));
alert((9, 0));
alert(("foo", "bar"));

Also, have a look at the Firebug console if you want to try this out interactively.

Douglas
Lol, it's fun: `alert("1", alert("2", alert("3")))`
Topera
@Douglas, only the first argument is used in all cases. I'd imagine you would expect the same to happen in your own code (if you had a function that took one argument but then provided it two). And @Topera, your code demonstrates that when you pass a function/method as an argument, it will get evaluated immediately, even if it is not used.
Andrew
@Andrew: Oops, I've updated my answer with what I meant to use.
Douglas