A2oz

What are assignment operators in JavaScript?

Published in JavaScript Fundamentals 2 mins read

Assignment operators in JavaScript are special symbols that allow you to assign values to variables. They are used to assign the result of an expression to a variable.

Types of Assignment Operators:

Here are some common assignment operators in JavaScript:

  • = (Assignment Operator): This is the most basic assignment operator. It assigns the value on the right to the variable on the left.

      let x = 10; // Assigns the value 10 to the variable x
  • += (Addition Assignment): Adds the right operand to the left operand and assigns the result to the left operand.

      let x = 5;
      x += 3; // x is now 8 (5 + 3)
  • -= (Subtraction Assignment): Subtracts the right operand from the left operand and assigns the result to the left operand.

      let x = 10;
      x -= 5; // x is now 5 (10 - 5)
  • *`=` (Multiplication Assignment):** Multiplies the left operand by the right operand and assigns the result to the left operand.

      let x = 5;
      x *= 2; // x is now 10 (5 * 2)
  • /= (Division Assignment): Divides the left operand by the right operand and assigns the result to the left operand.

      let x = 10;
      x /= 2; // x is now 5 (10 / 2)
  • %= (Modulo Assignment): Divides the left operand by the right operand and assigns the remainder to the left operand.

      let x = 10;
      x %= 3; // x is now 1 (10 % 3)
  • `=` (Exponentiation Assignment):** Raises the left operand to the power of the right operand and assigns the result to the left operand.

      let x = 2;
      x **= 3; // x is now 8 (2 * 2 * 2)

Practical Insights:

  • Assignment operators are essential for manipulating data in JavaScript.
  • They make your code more concise and efficient by combining operations.
  • Understanding these operators is crucial for writing effective JavaScript programs.

Related Articles