Assignment Operators in JavaScript

Purpose
  • Assignment operators are used to assign a value to a variable.
  • They provide a shorthand way to perform an operation on a variable and then assign the result back to the same variable.
Common Assignment Operators:
  1. = (Simple Assignment): Assigns the value on the right-hand side to the variable on the left-hand side.
    • let x = 5; /* Assigns the value 5 to the variable x*/
  2. += (Addition Assignment): Adds the value on the right-hand side to the variable and assigns the result back to the variable.
    • let x = 5:
      x += 3; /* Equivalent to x = x + 3; (x will now be 8)*/
  3. -= (Subtraction Assignment): Subtracts the value on the right-hand side from the variable and assigns the result back to the variable.
    • let x = 10;
      x -= 3; /* Equivalent to x = x - 3; (x will now be 7)*/
  4. *= (Multiplication Assignment): Multiplies the variable by the value on the right-hand side and assigns the result back to the variable.
    • let x = 5;
      x *= 3; /* Equivalent to x = x * 3; (x will now be 15)*/
  5. /= (Division Assignment): Divides the variable by the value on the right-hand side and assigns the result back to the variable.
    • let x = 10;
      x /= 2; /* Equivalent to x = x / 2; (x will now be 5)*/
  6. %= (Modulo Assignment): Performs the modulo operation (returns the remainder of the division) and assigns the result back to the variable.
    • let x = 10;
      x %= 3; /* Equivalent to x = x % 3; (x will now be 1)*/
  7. **= (Exponentiation Assignment): Raises the variable to the power of the value on the right-hand side and assigns the result back to the variable.
    • let x = 2;
      x **= 3; /* Equivalent to x = x ** 3; (x will now be 8)*/
Benefits of Using Assignment Operators:
  • Shorter and more concise code: They provide a more compact way to perform operations and assignments.
  • Improved readability: In some cases, assignment operators can make the code easier to read and understand.
Scroll to Top