What is difference between addition assignment operator and plus operator with blank string?

  • A+
Category:Languages

I have a code as below:

var point = ''; point = '' + 12 + 34; console.log(point); // output = 1234

var point = ''; point += + 12 + 34; console.log(point); //output = 46

Could you explain about it?

Thanks.

 


The difference is grouping. This:

point += + 12 + 34; 

is equivalent to:

//              v-----------v---- note grouping point = point + ( + 12 + 34 ); //                ^--- unary 

The indicated + is a unary + which doesn't do anything there since 12 is already a number. So we have:

point = point + ( 12 + 34 ); 

which is:

point = point + 46; 

which, since point starts out being "", is "46" (a string).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: