Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 942
dieuhd Avatar asked Dec 03 '22 11:12

dieuhd


1 Answers

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).

like image 148
T.J. Crowder Avatar answered Mar 13 '23 00:03

T.J. Crowder