Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`x = y, z` comma assignment in JavaScript [duplicate]

Tags:

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?

like image 739
Yatharth Agarwal Avatar asked Oct 07 '12 15:10

Yatharth Agarwal


People also ask

How do you write commas in JavaScript?

A comma operator (,) in JavaScript is used in the same way as it is used in many programming languages like C, C++ etc. This operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand.

How is comma operator useful in a for loop?

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

What is assignment in JavaScript?

Assignment (=) The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.

What is the use of comma operator in C?

The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.


1 Answers

This is the comma operator.

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

The resultant value when a,b,c,...,n is evaluated will always be the value of the rightmost expression, however all expressions in the chain are still evaluated (from left to right).


So in your case, the assignations would still be evaluated, but the final value would be bassoon.

Result:

galleons = brigantines brigantines = bassoon armada.embrace(basson) 

More information: Javascript "tuple" notation: what is its point?

like image 200
mbinette Avatar answered Mar 10 '23 21:03

mbinette