A metal sculpture resembling the seam on a baseball

Compound assignment operators can be thought of as simple shortcuts to mathematical expressions. An assignment operator assigns a value to its left operand as the result of operating on its right operand.

The simplest possible operand is the = operator:

var x = y;

…which assigns the value of y to x. It’s also possible to chain = operators together. If we have several variables a, b and c:

var a = 5,
b = 10,
c = 15;

We can create the expression:

a = b = c;

…which will set the value of both a and b to 15. (You could read the expression as “a is equal to b which is equal to c”).

More complex combined assignment operators include:

NameShorthand OperatorEquivalent To
Additionx += yx = x + y
Subtractionx -= yx = x - y
Multiplicationx *= yx = x * y
Divisionx /= yx = x / y
Remainderx %= yx = x % y

Because addition is also concatenation in JavaScript, the += assignment operator is often used to merge strings:

var welcome = "Good ";
var time = "morning";
welcome += time;
console.log(welcome);

> Good morning

Note that these operators always alter the value of the left operand (the x variable, in this case). If you wanted to preserve the original value of the variable for future reference, you’d have to assign the result to a new variable:

var z = x + y;

Additional Quirks

As with the ordinary addition operator, there are a few oddities, due to the fact that addition also works to concatenate:

If we have a variable named boo that has a Boolean true value:

var boo = true; 

Then adding a boolean or a number to it will result in numerical addition:

boo += true
> 2
boo += 2
> 4

boo now contains a numerical value; adding a string to it will result in concatenation:

boo += "scary"
> "4scary"

Adding a string to a boolean value also results in concatenation.

Do you have to use assignment operators?

Compound assignment operators can appear confusing at first. It’s important to remember that they’re just JavaScript shorthand: a more compact way of writing things. Feel free to use the more traditional “longhand” methods if you want to; just know that an alternative exists, and try them out once in a while to see if they fit your coding style.

There are also more complex assignment operators, some of them introduced in the most recent version of JavaScript, which I’ll cover in the next article.

Image by fdecomite, licensed under Creative Commons

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.