Reputation: 3481
I've read about the comma operator in JS but I am not sure whether this operator is used in expressions like this:
var a, b, c;
Is this the comma operator at work or is the comma used here just part of the syntax for declaring multiple variables and thus nothing to do with the comma operator?
Similarly, what about code that declares an array literal:
var x = [ 1, 2, 3 ];
It seems to me that comma operator syntax requires parentheses around the expression, for example:
x = (2, 3);
but this was not explicitly noted in the MDN article. If this is the case then is it true that the first two snippets here are not using the comma operator because there are no parentheses around it?
Upvotes: 3
Views: 111
Reputation: 414086
The comma operator is indeed strange, and it takes some time to get used to the nuances.
In var
, const
, and let
declarations, the comma separates the variables (and their initialization expressions, if any). In that case, without (as you note) parenthesized commas, the comma is only a syntactic separator token. However, inside an initalizer expression that does have commas, then that's the comma operator.
Similarly, in an array initializer, the commas are separators for the array values, but once again parentheses introduce a new expression context.
Same goes for the commas in object initializers and in function calls and function declarations.
It's not always the case that comma operator expressions must be parenthesized. In fact some code minimizers try to replace semicolons with commas (for arcane reasons).
In practice, the most useful purpose of the comma operator is to be able to squeeze more than one expression (generally ones with side-effects) into a slot in some larger syntax that allows for one expression. A for
loop is a good example:
for (*expression*; *expression*; *expression*) { ... }
The comma operator would let you do two things in one of those expressions:
for (let i = 0; i < 10; someFunction(i), i++) { ... }
Upvotes: 3
Reputation: 1075895
Is this comma operator at work or is the comma used here just part of the syntax for declaring multiple variables and thus has nothing to do with the comma operator?
The latter, it's just part of the var
(and let
and const
) syntax.
It seems to me that comma operator syntax requires parentheses around the expression
You often find you want them because otherwise the expression is grouped in another way; the comma operator has very low precedence, so just about everything is going to win out over it. But you don't always need them, just almost always. This contrived example gets away without them, for instance:
console.log(1), console.log(2);
Upvotes: 2