JavaScript Assignment Operators
5 April 2025 | Category: JavaScript
📌 What are Assignment Operators?
In JavaScript, assignment operators are used to assign values to variables. They are also used to perform operations like addition, subtraction, multiplication, etc., and then assign the result back to the variable.
đź§® 1. Basic Assignment Operator: =
let a = 10;
Explanation:
The =
operator assigns the value 10
to the variable a
.
âž• 2. Addition Assignment: +=
let x = 5;
x += 3; // same as x = x + 3
console.log(x); // Output: 8
Explanation:x += 3
adds 3
to the current value of x
and assigns the result back to x
.
âž– 3. Subtraction Assignment: -=
let y = 10;
y -= 4; // same as y = y - 4
console.log(y); // Output: 6
Explanation:y -= 4
subtracts 4
from y
and assigns the result back to y
.
✖️ 4. Multiplication Assignment: *=
let z = 6;
z *= 2; // same as z = z * 2
console.log(z); // Output: 12
Explanation:z *= 2
multiplies z
by 2
and updates the value of z
.
âž— 5. Division Assignment: /=
let a = 20;
a /= 5; // same as a = a / 5
console.log(a); // Output: 4
Explanation:a /= 5
divides a
by 5
and stores the result in a
.
6. Modulus Assignment: %=
let b = 10;
b %= 3; // same as b = b % 3
console.log(b); // Output: 1
Explanation:b %= 3
calculates the remainder when b
is divided by 3
.
7. Exponentiation Assignment: **=
let c = 2;
c **= 3; // same as c = c ** 3
console.log(c); // Output: 8
Explanation:c **= 3
raises c
to the power of 3
(2Âł = 8).
âś… Summary Table
Operator | Example | Same As | Meaning |
---|---|---|---|
= | x = y | x = y | Assign y to x |
+= | x += y | x = x + y | Add y to x |
-= | x -= y | x = x – y | Subtract y from x |
*= | x *= y | x = x * y | Multiply x by y |
/= | x /= y | x = x / y | Divide x by y |
%= | x %= y | x = x % y | x becomes the remainder |
**= | x **= y | x = x ** y | x raised to the power of y |
🔚 Conclusion
Assignment operators help you write cleaner and shorter code when updating the value of a variable. They are very common in loops, conditional logic, and when performing calculations.