Possible Duplicate:
Javascript syntax: what comma means?
I came across the code while reading this article (do a Ctrl+F search for Andre Breton
):
//function returning array of `umbrella` fibonacci numbers
function Colette(umbrella) {
var staircase = 0, galleons = 0, brigantines = 1, armada = [galleons, brigantines], bassoon;
Array.prototype.embrace = [].push;
while(2 + staircase++ < umbrella) {
bassoon = galleons + brigantines;
armada.embrace(brigantines = (galleons = brigantines, bassoon));
}
return armada;
}
What does the x = (y = x, z)
construct mean? Or more specifically, what does the y = x, z
mean? I'm calling it comma assignment because it looks like assignment and has a comma.
In Python, it meant tuple unpacking (or packing in this case). Is it the same case here?
This is the comma operator.
So in your case, the assignations would still be evaluated, but the final value would be
bassoon
.Result:
More information: Javascript "tuple" notation: what is its point?
The comma operand evaluates all of its operands and returns the last one. It makes no difference in this case if we had used
or
It's there to take away that line of code.
var
syntax allows multiple assignment, so when you see the following, you're declaring multiple variables using onevar
statement.Note that this syntax is not the comma operator.
The
,
can be used as the comma operator. It simply evaluates a series of expressions. So when you see the following syntax, you are seeing a series of expressions being evaluated, and the return value of the last one being returned.Within the parens,
x
is assigned toy
, thenz
is evaluated and returned from the()
and assigned tox
.I'd suggest that this syntax is unclear and offers little benefit.