Skip to content

More Assignment Operators

There are a few miscellaneous operators that are useful. We call them Compound Assignment Operators.

Compound Assignment Operators

Operators Function
+= Adds to a variable
-= Subtract to a variable
*= Multiply into a variable
/= Divide into a variable

Adding into a variable +=

We can add a number to a variable like this:

1
2
3
4
5
6
7
// Adding with +
let myNumber;

myNumber = 0;
myNumber = myNumber + 10;

document.write("myNumber: " + myNumber);

And we can use a shortcut Compound Assignment Operator too. Since this is less typing we have fewer chances of making an error. Also, this is the way you will see professional programmers do it.

1
2
3
4
5
6
7
// Adding with +=
let myNumber;

myNumber = 0;
myNumber += 10;

document.write("myNumber: " + myNumber);


Subtracting into a variable -=

We can subtract a number from a variable like this:

1
2
3
4
5
6
7
// Subtracting with -
let myNumber;

myNumber = 100;
myNumber = myNumber - 10;

document.write("myNumber: " + myNumber);

And we can use a shortcut Compound Assignment Operator too. Since this is less typing we have fewer chances of making an error. Just like with addition, this is the way you will see professional programmers do it.

1
2
3
4
5
6
7
// Subtracting with -=
let myNumber;

myNumber = 100;
myNumber -= 10;

document.write("myNumber: " + myNumber);


Multiplying into a variable *=

As you might now guess, we can also multiply into a variable like this:

1
2
3
4
5
6
7
// Multiplying with *
let myNumber;

myNumber = 100;
myNumber = myNumber * 2;

document.write("myNumber: " + myNumber);

This works too and it the preferred way to do it:

1
2
3
4
5
6
7
// Multiplying with *=
let myNumber;

myNumber = 100;
myNumber *= 2;

document.write("myNumber: " + myNumber);

Dividing into a variable /=

I think you could figure out that this one was coming! Dividing like this:

1
2
3
4
5
6
7
// Dividing with /
let myNumber;

myNumber = 100;
myNumber = myNumber / 2;

document.write("myNumber: " + myNumber);

But, dividing like this is better:

1
2
3
4
5
6
7
// Dividing with /=
let myNumber;

myNumber = 100;
myNumber /= 2;

document.write("myNumber: " + myNumber);

Labs

  1. Lab09: Compound Assignment Operators
    • unit02/labs/lab-09-compoundAssignmentOperators.html

Exercises

  1. Exercise for lab09
    • unit02/exercises/exercise-09.html