JavaScript Assignment Operators
Assignment Operators in JavaScript
Assignment operators in JavaScript are used to assign values to variables. They not only assign values but can also perform mathematical operations while assigning. This guide will walk you through the various assignment operators, explaining how each one works with clear examples.
= Operator in JavaScript
The =
operator assigns the value of the right-hand operand to the left-hand variable.
Example:
javascript
1let x = 20; // Assigns 20 to x
2let y = x + 10; // Assigns 30 to y (20 + 10)
3console.log(x); // Output: 20
4console.log(y); // Output: 30
+= Operator in JavaScript
The +=
operator adds the right-hand operand to the left-hand variable and assigns the result to the left-hand variable.
Example:
javascript
1let a = 15;
2a += 10; // Equivalent to a = a + 10
3console.log(a); // Output: 25
String Example:
javascript
1let text = "Hello";
2text += " JavaScript!";
3console.log(text); // Output: Hello JavaScript!
-= Operator in JavaScript
The -=
operator subtracts the right-hand operand from the left-hand variable and assigns the result to the left-hand variable.
Example:
javascript
1let b = 20;
2b -= 5; // Equivalent to b = b - 5
3console.log(b); // Output: 15
*= Operator in JavaScript
The *=
operator multiplies the left-hand variable by the right-hand operand and assigns the result to the left-hand variable.
Example:
javascript
1let c = 4;
2c *= 5; // Equivalent to c = c * 5
3console.log(c); // Output: 20
**= Operator in JavaScript
The **=
operator raises the left-hand variable to the power of the right-hand operand and assigns the result to the left-hand variable.
Example:
javascript
1let d = 3;
2d **= 3; // Equivalent to d = d ** 3 (3 to the power of 3)
3console.log(d); // Output: 27
/= Operator in JavaScript
The /=
operator divides the left-hand variable by the right-hand operand and assigns the result to the left-hand variable.
Example:
javascript
1let e = 50;
2e /= 5; // Equivalent to e = e / 5
3console.log(e); // Output: 10
4
%= Operator in JavaScript
The %=
operator calculates the remainder of the division of the left-hand variable by the right-hand operand and assigns it to the left-hand variable.
Example:
javascript
1let f = 29;
2f %= 6; // Equivalent to f = f % 6 (remainder of 29 divided by 6)
3console.log(f); // Output: 5