JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables. Beyond the basic = operator, compound assignment operators provide convenient shorthand for performing an operation and assignment in a single step, making code more concise and readable.

Assignment Operators

The basic assignment operator (=) assigns the value on the right side to the variable on the left side. For example, "let x = 5" assigns the value 5 to the variable x. The right side can be a literal value, another variable, or an expression that evaluates to a value. Assignment is right-to-left: the value flows from right to left.

The addition assignment operator (+=) adds the right operand to the variable and assigns the result back to that variable. Writing "x += 5" is shorthand for "x = x + 5". If x was 10, it becomes 15. This operator works with both numbers (adding) and strings (concatenating), making it versatile for different data types.

The subtraction assignment operator (-=) subtracts the right operand from the variable and assigns the result back to that variable. Writing "x -= 3" is equivalent to "x = x - 3". If x was 15, it becomes 12. This operator is commonly used for counting down, reducing quantities, or adjusting values downward.

The multiplication assignment operator (*=) multiplies the variable by the right operand and assigns the result back to that variable. Writing "x *= 2" is shorthand for "x = x * 2". If x was 12, it becomes 24. This operator is useful for doubling values, scaling quantities, or compound growth calculations.

The division assignment operator (/=) divides the variable by the right operand and assigns the result back to that variable. Writing "x /= 4" means "x = x / 4". If x was 24, it becomes 6. This operator is useful for splitting quantities, calculating averages, or reducing values proportionally.

The modulus assignment operator (%=) performs modulus division and assigns the remainder back to the variable. Writing "x %= 5" means "x = x % 5". If x was 6, it becomes 1 (6 divided by 5 leaves remainder 1). This operator is useful for wrapping values within ranges or implementing cyclic behavior.

// Simple assignment
let x = 10;

// Addition assignment
x += 5;  // Same as: x = x + 5 (x is now 15)

// Subtraction assignment
x -= 3;  // Same as: x = x - 3 (x is now 12)

// Multiplication assignment
x *= 2;  // Same as: x = x * 2 (x is now 24)

// Division assignment
x /= 4;  // Same as: x = x / 4 (x is now 6)

// Modulus assignment
x %= 5;  // Same as: x = x % 5 (x is now 1)