Return with multiple comma separated values

Possible duplicate:
Javascript syntax: what does a comma mean?

What returns this template? How it works?

return myfunc(), myobj.myvar = someobj.prop, myobj

I had not come across this pattern before, but looked at Bing Maps Ajax Control and noticed this pattern several times.

As I understand it, several values ​​are not returned. So what does this model do? What is coming back? What is the discount?

+67
javascript
Apr 23 2018-12-12T00:
source share
3 answers

This is a comma operator . It evaluates its left operand, discards the result, evaluates its right operand, and takes it as the value of the result. It is associative from left to right, so a, b, c evaluate a , then b , then c and take the result c as a value.

In your example, it is exactly like this:

 myfunc(); myobj.myvar = someobj.prop; return myobj; 

Some people really prefer to do something on the same line, even if there is no objective reason for this. There is no use in the example you cited, and in fact it is confusing, because it seems that the first two bits refer to the value that will ultimately be returned, which is not the case. (I wrote that before you told us that this is minimized code; it is obvious that obscurity for people is only a problem of source code, not minimized code.)

Since you said that this is a minifier, there is very little possible benefit that a minifier could have if it is part of a conditional block: it can store one or two characters. If we assume that the long form looked like this:

 if (someCondition) { myfunc(); myobj.myvar = someobj.prop; return myobj; } 

... using the comma operator, the minifier can do this (63 characters):

 if(someCondition)return myfunc(),myobj.myvar=someobj.prop,myobj 

... and not this (65 characters):

 if(someCondition){myfunc();myobj.myvar=someobj.prop;return myobj} 

... without changing the functionality of the code, if it follows } or any other appropriate character (or end of file) to start automatically inserting a semicolon at the end. Otherwise, it will be necessary ; on the first, but it still saves one character.

+120
Apr 23 2018-12-12T00:
source share

The comma operator evaluates (from left to right) the expression, and then returns the last result, which in this case will be the evaluation of myobj identifier.

You can remove some curly braces if this is important to you ...

 if (true) ;// do something else return myfunc(), myobj.myvar = someobj.prop, myobj 

... Unlike...

 if (true) ;// do something else { myfunc(); myobj.myvar = someobj.prop; return myobj; } 
+8
Apr 23 2018-12-12T00:
source share

in your example, myobj should be returned to where every thing before doing

 myfunc(); myobj.myvar = someobj.prop; return myobj; 
+1
Apr 23 2018-12-12T00:
source share



All Articles