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?
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.
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.
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 .
The subtraction assignment operator ( -= ) subtracts the value of the right operand from a variable and assigns the result to the variable.
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) { ... }
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