JavaScript Arithmetic Assignment Operators: A Quick Guide
This article is a complementary resource to the Learn JavaScript Basics course.
This article is a complementary resource to the Learn JavaScript Basics course.
Arithmetic assignment operators are shorthand operators in JavaScript that combine arithmetic operations and assignments in a single step.
Suppose you want to increase the value of a variable by 1:
let i = 10;
i = i + 1;
console.log(i); // Output: 11
This code adds 1 to the value of i and assigns the updated value back to the i variable.
In such cases, you can use arithmetic assignment operators to make the operation clearer and more concise:
let i = 10;
// Equivalent to: i = i + 1
i += 1;
console.log(i); // Output: 11
Here, the +=
operator adds 1 to the variable i and updates its value.
JavaScript supports arithmetic assignment operators for all standard arithmetic operators. Here's the summary:
Operator | Example | Equivalent To |
---|---|---|
+= |
x += 5 |
x = x + 5 |
-= |
x -= 5 |
x = x - 5 |
*= |
x *= 5 |
x = x * 5 |
/= |
x /= 5 |
x = x / 5 |
%= |
x %= 5 |
x = x % 5 |
**= |
x **= 5 |
x = x ** 5 |
Let's see some of these operators in practice.
let total = 100;
let discount = 20;
total -= discount;
console.log(total); // Output: 80
let number = 1000.0;
let divisor = 5;
number /= divisor;
number /= divisor;
console.log(number); // Output: 40.0
Now, try using arithmetic assignment operators in your code to make basic operations more concise and readable!