Assignment Operators Explained
What are Assignment Operators?
Assignment operators are used to:
- Assign values to variables
- Update existing values
Example:
let a = 10; // = is assignment operator
Why Use Assignment Operators?
- Helps update values easily
- Makes code shorter and cleaner
- Improves performance in large applications
List of Assignment Operators
| Operator | |
= | Assign |
+= | Add and assign |
-= | Subtract and assign |
*= | Multiply and assign |
/= | Divide and assign |
%= | Modulus and assign |
**= | Exponentiation and assign |
<<= | Left shift and assign |
>>= | Right shift and assign |
>>>= | Unsigned right shift and assign |
&= | Bitwise AND and assign |
| ` | =` |
^= | Bitwise XOR and assign |
Basic Example
let a = 10;
console.log(a); // 10
Updating Value (Normal Way)
let a = 10;
let b = 5;
a = a + b; // 15
Using Assignment Operator (Better Way)
let a = 10;
let b = 5;
a += b; // 15
- Same result as
a = a + b - Shorter and more efficient
Other Examples
Subtract and Assign
a -= b; // 10 - 5 = 5
Multiply and Assign
a *= b; // 10 * 5 = 50
Divide and Assign
a /= b;
Modulus and Assign
a %= b;
Exponentiation and Assign
a **= b; // 10^5
Function Example from Code
function operations() {
let a = 10;
let b = 5;
a **= b;
console.log(a);
}
Important Concept
Difference
a = a + b; // uses 2 operators
a += b; // uses 1 operator
+=is preferred in large projects- Improves readability and performance
Multiple Operations Example
let a = 10;
let b = 5;
a += b; // 15
a -= b; // 10
a *= b; // 50
Bitwise Assignment Operators (Basic Idea)
- Work on binary (0 and 1)
- Rarely used in normal projects
Examples:
a &= b; // AND
a |= b; // OR
a ^= b; // XOR
Shift Assignment Operators
- Also based on binary shifting
a <<= 1; // left shift
a >>= 1; // right shift
a >>>= 1; // unsigned right shift
- Mostly used in low-level operations
Important Notes
- Use
+=,-=,*=in real projects - Bitwise and shift operators are rarely used
- Assignment operators make code cleaner