TOC
Operators:

Modify-and-assign operators

We have now seen several variants of assignment operators, but there's one more type I want to talk about. It comes in different flavors, but the most commonly used is probably the addition assignment operator. There's a variant of this operator for the remaining three of the four basic arithmetic operators as well, but they don't seem to have a common name. I have seen them referred to as "modify-and-assign" operators for other programming languages, so that's the term we'll be using here as well.

The purpose of these operators is to help us modify a variable and immediately assign the new value back to the same variable. So whenever we want to do something like this:

let a = 5;
a = a + 5;
alert(a);

We can instead use one of these modify-and-assign operators, to shorten the code a bit. Let's see how they work.

Addition assignment operator: +=

With the addition assignment operator, which is the variant you'll see the most, the above code can be rewritten like this:

let a = 5;
a += 5;
alert(a);

We don't save a lot of keystrokes when the name of the variable is this short. Also, some people will argue that it makes the code less readable, while others like that it's less verbose - this is mostly a matter of personal preference.

Notice that the addition assignment operator can be used for strings as well:

let helloWorld = "Hello";
helloWorld += ", world!";
alert(helloWorld);

Subtraction assignment operator: -=

As promised, this type of operator comes in a variant for all the arithmetic operators - here's the subtraction variant:

let a = 15;
a -= 5;
alert(a);

This variant is for numbers only though - it won't work for strings, unless it can convert these strings into numbers:

let a = "15";
a -= "5";
alert(a);

Multiplication assignment operator: *=

You can use the multiplication assignment operator for doing multiplications:

let a = 5;
a *= 2;
alert(a);

Just like the subtraction assignment operator, this only works with numbers.

Division assignment operator: /=

And for the last one, the division assignment operator:

let a = 20;
a /= 2;
alert(a);

Only works for numbers as well.

Summary

The modify-and-assign operators are nice to have for quickly modifying a variable and assigning the new value back to the original variable. This operator type is mainly syntactic sugar, but you'll run into it a lot when reading other peoples code, especially the addition assignment operator (for both numbers and strings), while the other variants are less frequently used.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!