How does the comma operator work in js?

有些话、适合烂在心里 提交于 2019-12-28 06:59:31

问题


I'm trying to understand how the comma operator (,) works in JavaScript, it seems to have a different behaviour when it's not put between parenthesis.

Can someone explain me why ?

Exemple for reference :

var a = 1; 
var b = 2; 
var c = (a,b);
console.log(c);
//output : as expected 
var c = a,b;
console.log(c);
//output : 1 

[EDIT] The title might be a bit confusing. My question is about a misconception between the coma operator and var attribution as somone explained further down

Therefore this subject is not a duplicate of that one What does a comma do in JavaScript expressions?


回答1:


var c = (a,b);

The above uses the comma operator. It evaluates as the value of its right-hand side (i.e. b).


var c = a,b;

This does not use the comma operator.

The comma character here forms part of the var expression which takes a comma-separated list of variables to create in the current scope, each of which can have an optional assignment.

It is equivalent to:

var c = a;
var b;


来源:https://stackoverflow.com/questions/50678527/how-does-the-comma-operator-work-in-js

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