JavaScript Assignment Operators


What Are Assignment Operators?


Assignment operators are used to assign values to variables. The most basic one is = , but JavaScript also provides compound operators that perform an operation and assignment at the same time.


List of Assignment Operators

Operator Name Description Example Output
= Assignment Assigns right value to left variable x = 10 10
+= Add and assign x = x + y x += 5 15
-= Subtract and assign x = x - y x -= 2 13
*= Multiply and assign x = x * y x *= 2 26
/= Divide and assign x = x / y x /= 2 13
%= Modulus and assign x = x % y x %= 4 1
**= Exponent and assign x = x ** y x **= 3 1
<<=< /td> Left shift and assign x = x << y (bitwise left shift) x <<= 1 2
>>= Right shift and assign x = x >> y (bitwise right shift) x >>= 1 1
&= AND and assign x = x & y (bitwise AND) x &= 1 1
^= XOR and assign x = x ^ y (bitwise XOR) x ^= 3 2
` = ` OR and assign x = x | y (bitwise OR) ` x

1. Basic Assignment (=)


Assigns a value to a variable.

let a = 10;
console.log(a); // Output: 10

2. Add and Assign (+=)


Adds and then assigns the result to the variable.

let x = 10;
x += 5; // Equivalent to: x = x + 5
console.log(x); // Output: 15

3. Subtract and Assign (-=)

let x = 15;
x -= 2; // x = x - 2
console.log(x); // Output: 13

4. Multiply and Assign (*=)

let x = 13;
x *= 2; // x = x * 2
console.log(x); // Output: 26

5. Divide and Assign (/=)

let x = 26;
x /= 2; // x = x / 2
console.log(x); // Output: 13

6. Modulus and Assign (%=)

let x = 13;
x %= 4; // x = x % 4
console.log(x); // Output: 1

7. Exponentiation and Assign (**=)

let x = 2;
x **= 3; // x = x ** 3
console.log(x); // Output: 8

Bitwise Assignment Operators (Advanced)


Left Shift and Assign (<<=)< /h3>
let x = 1;
x <<= 2; // x = x << 2 (binary left shift)
console.log(x); // Output: 4

Right Shift and Assign (>>=)

let x = 4;
x >>= 1; // x = x >> 1
console.log(x); // Output: 2

Summary Table

Expression Equivalent To Result
x = 10 Assign 10 10
x += 5 x = x + 5 15
x -= 2 x = x - 2 13
x *= 2 x = x * 2 26
x /= 2 x = x / 2 13
x %= 4 x = x % 4 1
x **= 2 x = x ** 2 1