Advanced freeCodeCamp • lecture-working-with-operator-behavior

What Are Compound Assignment Operators in JavaScript and How Do They Work?

Lesson Overview

Compound assignment operators in JavaScript are shorthand notations that combine an arithmetic or bitwise operation with an assignment. They allow you to perform a calculation and update a variable...

Compound assignment operators in JavaScript are shorthand notations that combine an arithmetic or bitwise operation with an assignment. They allow you to perform a calculation and update a variable’s value in a single, concise step, which improves code readability and reduces redundancy.

How They Work

Instead of writing a statement that repeats the variable name on both sides of the assignment operator (e.g., x = x + 5), you can use a compound assignment operator to achieve the same result more efficiently (e.g., x += 5).

The operator performs the specified operation on the variable’s current value and the value on the right, and then assigns the final result back to that same variable.

Common Compound Assignment Operators

OperatorNameEquivalent To
+=Addition assignmentx = x + y
-=Subtraction assignmentx = x - y
*=Multiplication assignmentx = x * y
/=Division assignmentx = x / y
%=Modulus assignmentx = x % y
**=Exponentiation assignmentx = x ** y

Key Takeaways

  • Conciseness: They make code cleaner by eliminating the need to repeat the variable name.
  • Efficiency: By combining the operation and assignment, they help reduce typing errors and make code easier to maintain.
  • Associativity: Like the basic assignment operator (=), compound assignment operators are right-associative.
  • Versatility: Beyond basic arithmetic, other compound operators exist for bitwise operations (such as <<=, >>=, &=, |=, etc.).