Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x+=y+=z in Javascript

Tags:

javascript

I know in javascript

x = y = z means x = z and y = z

x+=z means x=x+z;

So if I want x=x+z and y=y+z, I tried x+=y+=z not working

anyone have a better idea to write short code instead x+=z;y+=z

EDIT

First thanks for everyone involved in my question. Here I wanna explain something why I have this question in first place.

I tried to write some code like x+='some html code', and I need to y+='the same html code'. So naturally I do not want to create another var z='the html code first then do x+=z and y+=z

Hope my explain make sense. Anyway, I am going to close this question now. Thanks again.

like image 691
Eric Yin Avatar asked May 14 '12 12:05

Eric Yin


People also ask

What is Z in JavaScript?

By doing "The value of z is " + z the operator is trying to do some work on a string and a number. The default behavior in this case is to type cast z as a string and then perform concatenation. Thus, at the end of this operation the output becomes the string "The value of z is 11 ".

What does $() mean in JavaScript?

Usually when you encounter $() , that means the developer is using a javascript library, such as jQuery. The $ symbol is the namespace for those libraries. All the functions they define begin with $. , such as $. get() .

Is it += or =+ in JavaScript?

the correct syntax is a+=b; a=+b; is not correct. it is simply assigning b value to a.


2 Answers

Assuming addition, and not concatenation, this works:

x -= y - (y += z);

but seriously, don't use it !


For those that want to figure out how, the sequence of evaluation (where I use n to show the current intermediate result) is approximately:

n = y1 = y0 + z  //    n = y = (y + z)
n = y0 - y1      // -> n == -z  [uses the original value of y]
x -= n           // -> x += z
like image 196
Alnitak Avatar answered Oct 10 '22 09:10

Alnitak


Just use this:

x+=z;y+=z

Honestly, anything else is just going to cause somebody else maintaining your code to stop and scratch their head for a couple of minutes. This code isn't shockingly long either...

like image 28
Paddy Avatar answered Oct 10 '22 07:10

Paddy