In JavaScript, all arithmetic operators have a compound assignment form. Compound assignment operators allow you to perform a mathematical operation and reassign the result back to the variable in one line of code. Instead of writing something like this:

let num = 5;
num = num + 2;
 
console.log(num); // 7

You can write something like this:

let num = 5;
num += 2;
 
console.log(num); // 7

Notice how num += 2 combines both the addition and assignment steps into one. This saves time and reduces clutter in your code. Let’s dive deeper into the most common compound assignment operators in JavaScript.

As you’ve already seen, the += operator lets you add a value to an existing variable. It is known as the addition assignment operator. The addition assignment operator takes the current value of the variable, adds the specified number to it, and then assigns the result back to the variable:

let total = 10;
total += 5;
 
console.log(total); // 15

As you might guess, there’s a subtraction assignment operator denoted by -=. The subtraction assignment operator subtracts the specified value from the current value of the variable and assigns the new value back to the variable:

let score = 20;
score -= 7;
 
console.log(score); // 13

If you didn’t use the subtraction assignment, you’d have done something like this:

let score = 20;
score = score - 7;
 
console.log(score); // 13

The multiplication assignment operator is represented by *=. It multiplies the current value of the variable by the specified number and reassigns it back to the variable:

let points = 5;
points *= 3;
 
console.log(points); // 15

Lastly, there’s a division assignment operator denoted by /=. Just like others before it, it lets you divide the current value of a variable by a number you specify, then assign the result back to the variable:

let balance = 100;
balance /= 4;
 
console.log(balance); // 25

Remember there’s a compound assignment operator for every operator in JavaScript. So, apart from the four already mentioned, we also have:

  • Remainder assignment operator (%=), which divides a variable by the specified number and assigns the remainder to the variable.

  • Exponent assignment operator (**=), which raises a variable to the power of the specified number and reassigns the result to the variable.

  • Bitwise AND assignment operator (&=), which performs a bitwise AND operation with the specified number and reassigns the result to the variable.

  • Bitwise OR assignment operator (|=), which performs a bitwise OR operation with the specified number and reassigns the result to the variable.