Pete
Pete

Reputation: 167

Javascript concatenate + and assign +=?

I'm reading a book on Javascript I've got to a confusing part regarding assignment operators and concatenation. Please see below code

var msg = 'JavaScript'; msg += ' Code'; //Concatenate
var intA = 8; intA -= 4; //Subtract and assign
var intB = 24; intB *= intA; //Multiply and assign

var str = 'Add & assign string: ' + msg;
    str += '<br>Multiply & assign: ' + initB;

I get that the += operator, when dealing with strings concatenates the two operands and when dealing with numbers they add the values of the operands and reassign to the computed value to first operand.

I also get that str is being initialised as 'Add & assign string ' + msg; and then appended with another string and a variable.

But why would you not just write the below in the example of the str variable?

var str = 'Add & assign string ' + msg + '<br>Multiply & assign: ' + initB;

Am I misunderstanding a subtle difference between + and += , or are they the same thing in this use case?

Upvotes: 2

Views: 3549

Answers (1)

Pointy
Pointy

Reputation: 413915

An expression like

a += b

is interpreted (almost) exactly as if it were written

a = a + b

Contrived examples explaining language constructs are contrived, and do not necessarily reflect common practice. (It'd be nice if they did, but creating code examples is notoriously difficult.)

Upvotes: 4

Related Questions