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?
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With