What does (1, 2) mean? Javascript?

I know that in javascript the syntax (1, 'a', 5, ... 'b') will always return the last value, but what does this syntax mean? When I see (1, 2) - which, admittedly, almost never - how should I parse this syntax?

+7
source share
5 answers

It is just a comma operator that evaluates two expressions and returns the second. Since it evaluates the arguments from left to right, if you have a list of arguments separated by commas, the latter will be returned. From JavaScript Style Elements :

The comma operator was borrowed, like most JavaScript syntax, from C. The comma operator takes two values ​​and returns the second. Its presence in a language definition tends to mask certain coding errors, so compilers tend to be blind to some errors. It is best to avoid the comma operator and use a comma separator instead.

+1
source

Separate expressions - a bit between commas - are evaluated, then the general expression takes on the value of the latter. Therefore, listing a number of numeric and string literals, such as your example, is pointless:

 (1, 'a', 5, ... 'b') // does the same thing as ('b') 

... so that you could leave everything but the last. However, if individual expressions have different effects because they are functional calls or assignments, you cannot leave them.

The one good reason I can think of using this syntax is in the for statement, because the for syntax is:

 for([init]; [condition]; [final-expression]) 

... does not allow the use of semicolons in the [init] or in the [condition] or [final-expression] parts. But you can include multiple expressions with commas:

 for(x = 0, y = 100, z = 1000; x < y; x++, y--, z-=100) { ... } 
+5
source

The operator evaluates both arguments and returns the last.

It is most often used in for loops:

 for( i=0, j=0; ...) 

Mdn docs

+2
source

The comma operator evaluates each element, and then returns the last:

 var x = (1, 2, 3); console.log(x == 3); // true 

Here's the Mozilla Documentation .

+2
source

Brackets are just a priority change operator. Therefore, in this case you can omit them.

And you go away with 1, 2 , which is just two expressions separated by a comma.

0
source

All Articles