Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 

[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?

like image 473
lekda Avatar asked Jun 04 '18 10:06

lekda


People also ask

Is comma required in JavaScript?

JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals, and more recently, to function parameters and to named imports and named exports. JSON, however, disallows trailing commas.

What are the uses of comma and conditional (?) Operators?

The comma operator (,) allows you to evaluate multiple expressions wherever a single expression is allowed. The comma operator evaluates the left operand, then the right operand, and then returns the result of the right operand. First the left operand of the comma operator is evaluated, which increments x from 1 to 2.

How does comma operator work 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

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;
like image 164
Quentin Avatar answered Sep 23 '22 15:09

Quentin