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

丶灬走出姿态 提交于 2019-11-30 08:21:39
mbinette

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?

var syntax allows multiple assignment, so when you see the following, you're declaring multiple variables using one var statement.

var a, b, c;

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.

x = (y = x, z)

Within the parens, x is assigned to y, then z is evaluated and returned from the () and assigned to x.


I'd suggest that this syntax is unclear and offers little benefit.

The comma operand evaluates all of its operands and returns the last one. It makes no difference in this case if we had used

x = (y = x, z);

or

y = x;

x = z;

It's there to take away that line of code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!