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
var x = y;
…which assigns the value of
x. It’s also possible to chain
= operators together. If we have several variables
var a = 5, b = 10, c = 15;
We can create the expression:
a = b = c;
…which will set the value of both
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:
|Name||Shorthand Operator||Equivalent To|
+= 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;
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
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?
Image by fdecomite, licensed under Creative Commons
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.