Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - What does (1, 2) actually mean?

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

like image 523
George Mauer Avatar asked Aug 23 '12 21:08

George Mauer


People also ask

What does 1 mean in JavaScript?

No, -1, 0, and 1 in a comparison function are used to tell the caller how the first value should be sorted in relation to the second one. -1 means the first goes before the second, 1 means it goes after, and 0 means they're equivalent.

What is the result of 1 1 in JavaScript?

In javascript + indicates concatination. That's why when you try to add a number(i.e. 1) to a string ('1'),it becomes 11. And it treats * as multipication, so it multiplies a number (1) with a string ('1') and gives result as 1.

What is the result of 2 2 in JavaScript?

So the first "2" and second "2" makes "22". But when performing subtraction ( - ) on strings, coercion happens. So the resulted "22" coerced to number 22 and final "2" coerced to number 2 . Finally subtracts 2 from 22 to result 20 .

What does =- mean in JavaScript?

The subtraction assignment operator ( -= ) subtracts the value of the right operand from a variable and assigns the result to the variable.


1 Answers

The individual expressions - the bits between the commas - are evaluated, then the overall expression takes the value of the last one. So listing a series of numeric and string literals like your example is kind of pointless:

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

...so you might as well leave out all but the last. However if the individual expressions have other effects because they are function calls or assignments then you can't leave them out.

About the only good reason I can think of to use this syntax is within a for statement, because for syntax:

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

...doesn't allow you to use semicolons within the [init] part, or within the [condition] or [final-expression] parts. But you can include multiple expressions using commas:

for(x = 0, y = 100, z = 1000; x < y; x++, y--, z-=100) { ... }
like image 121
nnnnnn Avatar answered Sep 22 '22 20:09

nnnnnn