Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

javascript - How does the comma operator work in js?

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 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...