views:

181

answers:

2

.

var a,b,c = function() { return 5; };

Variables a and b is undefined, c is function, why when we do this (a,b,c)() we have 5 ?

+10  A: 

Because (a,b,c) evaluates to c.

See the comma operator. Works the same way in C, C++.

Alex
Definitely not in C#. It's not an operator and only works as a separator for declarations when all the declared variables have the same type. I'm pretty sure it's the same in Java.
DrJokepu
Ah, ok. I wasn't sure about the last two :) Thanks.
Alex
What happens if b is set to the function {return 5} instead of var c?
Drahcir
Then c is not a function and you get: "Exception thrown: c is not a function"
Marcel Korpel
+3  A: 

The declaration is the same as:

var a;
var b;
var c = function() { return 5; };

or practically the same as:

var a;
var b;
function c() { return 5; };

Using (a,b,c) has nothing to do with the declaration, it simply returns the last operand, so (a,b,c)() is exactly the same as c() (as long as evaluating a and b doesn't have any side effects).

Guffa
`c = function(){…}` is *not* the same as `function c(){…}`!
Gumbo
@Gumbo: Yes, they are not exactly the same, but in this case there is no practical difference. I changed the answer so that it doesn't imply that it's the exact same thing. :)
Guffa