📝 Assignment & Compound Operators in JavaScript
Last Updated: 11th Oct 2025
📌 What is Assignment (=)?
- The assignment operator (
=) is used to store a value in a variable. - It assigns the value on the right side to the variable on the left side.
Hinglish Tip 🗣:
=ka matlab hai “value ko variable ke andar daal do” — jaisex = 10matlabxke andar 10 store ho gaya.
Example:
let x = 10; // x holds 10
let y = 5; // y holds 5
📌 Compound Operator
Compound assignment operators combine an operation and assignment in one step.
- Instead of writing x = x + 5, you can write x += 5.
- They work for arithmetic and bitwise operations.
Hinglish Tip 🗣: x += 5 ek chhota shortcut hai x = x + 5 ka.
| Operator | Meaning | Equivalent Long Form |
|---|---|---|
| = | Assign | x = 10 |
| += | Add and assign | x += 5 → x = x + 5 |
| -= | Subtract and assign | x -= 3 → x = x - 3 |
| *= | Multiply and assign | x *= 2 → x = x * 2 |
| /= | Divide and assign (float result) | x /= 4 → x = x / 4 |
| %= | Modulus and assign | x %= 3 → x = x % 3 |
| **= | Power and assign | x **= 2 → x = x ** 2 |
| &= | Bitwise AND and assign | x &= 3 → x = x & 3 |
| |= | Bitwise OR and assign | x |= 2 → x = x | 2 |
| ^= | Bitwise XOR and assign | x ^= 4 → x = x ^ 4 |
| <<= | Left shift and assign | x <<= 1 → x = x << 1 |
| >>= | Right shift and assign | x >>= 2 → x = x >> 2 |
Example
let x = 10;
x += 5; // x = x + 5
console.log(x); // 15
x -= 3; // x = x - 3
console.log(x); // 12
x *= 2; // x = x * 2
console.log(x); // 24
x /= 4; // x = x / 4
console.log(x); // 6
x **= 2; // x = x ** 2
console.log(x); // 36
let x = 10; // binary: 1010
x &= 6; // 1010 & 0110 = 0010 (2)
console.log(x); // 2
x |= 4; // 0010 | 0100 = 0110 (6)
console.log(x); // 6
x ^= 3; // 0110 ^ 0011 = 0101 (5)
console.log(x); // 5
💡 Tip: Compound operators save time and reduce typing. You’ll use them a lot in loops, counters, and calculations .Don’t worry! For Bitwise Operator ,We will cover in upcoming section.
💡 Quick Practice
- Create a variable count = 10 → add 5 using +=
- Subtract 2 using -= and print result
- Multiply by 3 using *=
- Divide by 2 using /=
- Print each result step-by-step in console