JavaScript : Assignment

In JavaScript, assignment operators are used to assign values to variables. They are a fundamental part of programming, allowing you to store and manipulate data in variables. Let's explore the different assignment operators available in JavaScript:

1. Assignment Operator (=):


The basic assignment operator ( ) assigns the value of the right operand to the variable on the left.


let x = 10;  // Assigns the value 10 to the variable x
 

2. Addition Assignment (+=):


The addition assignment operator (+= ) adds the value of the right operand to the variable and assigns the result to the variable.


let y = 5;
y += 3;  // Equivalent to: y = y + 3; Result: 8

 

3. Subtraction Assignment (-=):


The subtraction assignment operator (-=) subtracts the value of the right operand from the variable and assigns the result to the variable.


let z = 10;
z -= 5;  // Equivalent to: z = z - 5; Result: 5

 

4. Multiplication Assignment (*=):


The multiplication assignment operator (*=) multiplies the variable by the value of the right operand and assigns the result to the variable.


let a = 3;
a *= 4;  // Equivalent to: a = a * 4; Result: 12

 

5. Division Assignment (/=):


The division assignment operator ( /= ) divides the variable by the value of the right operand and assigns the result to the variable.


let b = 12;
b /= 3;  // Equivalent to: b = b / 3; Result: 4

 

6. Modulus Assignment (%=):


The modulus assignment operator (`%=`) divides the variable by the value of the right operand and assigns the remainder to the variable.


let c = 10;
c %= 3;  // Equivalent to: c = c % 3; Result: 1

 

Example Usage:

Here's an example demonstrating the use of assignment operators in JavaScript:


let num = 10;

num += 5;  // num = num + 5; Result: 15
console.log("After addition:", num);

num -= 3;  // num = num - 3; Result: 12
console.log("After subtraction:", num);

num *= 2;  // num = num * 2; Result: 24
console.log("After multiplication:", num);

num /= 4;  // num = num / 4; Result: 6
console.log("After division:", num);

num %= 4;  // num = num % 4; Result: 2
console.log("After modulus:", num);

 

Conclusion:


Assignment operators are essential for manipulating variables in JavaScript. They allow you to perform arithmetic operations and update the value of variables in a concise and efficient manner. By understanding how assignment operators work, you can effectively manage data in your JavaScript programs.