I’m writing the following code in the browser console in JavaScript, but the concept and syntax is applicable to a lot of programming languages.

In programming we have a number of mathematical operators that allow us to do the basic functions of maths such as addition, subtraction, multiplication and so forth. They look something like this:

>> 4 + 5 // addition
9
>> 4 - 5 // subtraction
-1
>> 4 * 5 // multiplication
20
>> 4 / 5 // division 
0.8
>> 4 % 5 // modulus (the remainder after division)
4 

If we bring a variable into the mix to allow for the storage of the result we can make calculations on the variable and assign the result back to itself. For example, if I want to do the above addition with a variable I could do this:

>> x = 4;
4
>> x = x + 5;
9

But that’s clunky and x is repeated. It doesn’t have to be like that if I use the augmented assignment operator. The augmented assignment operator sticks an operator to the left of an equals sign to perform the same function as above, but more elegantly:

>> x = 4;
4
>> x += 5;
9

In the above, the += is doing the same thing as x = x + 5;.

Also, we can do it with all the other arithmetic operators so, for subtraction:

>> x = 4;
4
>> x -= 5; 
-1

For multiplication:

>> x = 4;
4
>> x *= 5; 
20

For division:

>> x = 4;
4
>> x /= 5; 
0.8

For modulus:

>> x = 4;
4
>> x %= 5; 
4

The featured Image for this post is a photo by Chris Liverani on Unsplash.

Augmented Assignment Operators

Leave a Reply

Your email address will not be published. Required fields are marked *